How to get the connection id of a socket on a js Node server?

Asked

Viewed 709 times

2

Hello, I am studying sockets with Node js for games and I would like to know how to recover the id of a client socket connection with the server, I have tried several ways but did not succeed!

My client code is as follows::

var net = require('net');
var client = new net.Socket(); //Cria o socket do cliente
client.connect(3000, '127.0.0.1', function() { //Inicia o socket do cliente
    console.log('Conectado ao servidor');
    client.write('Olá servidor! De, Cliente.');
});
client.on('data', function(data) {
    console.log('Recebido: ' + data);
});

My server code is as follows:

var net     = require("net"); //Importa a biblioteca
var porta   = 3000; //Define qual porta o servidor vai escutar
var host    = "127.0.0.1";
var servidor = net.createServer(); //Cria o socket do servidor
servidor.listen(porta, function (socket){  //Roda o servidor
    console.log(`Servidor iniciado..`);
});
servidor.on('connection', function(socket){
    console.log(`Nova coneção`);
    socket.on('data', function(data){
        console.log(`Recebido: ` + data);
    })
});

How can I get the client connection/socket id to have a control on my server?

My code is very simple, I know very little and, I’m just studying how the sockets work in Ode, if you have suggestions for improvements or criticism I’m totally open to receiving them!!

2 answers

3

In general there is no concept of "connection id" in the TCP protocol. It is possible to know the IP address and port of the person who connected remotely, in his example the Ria through the socket.remoteAddress and socket.remotePort. However this does not serve as "connection id" as it has no uniqueness guaranteed.

The general solution of this problem lies in the scope of the application, that is, it is necessary to design an "application protocol", which in practice is simply the message formats that your server and client understand. For example, the first 3 bytes can identify the operation the client is asking the server for ("000" read, "001" write, etc.). One of these operations could be the client’s "identification", for example operation "009", then 5 digits with the client’s identification. This is just an illustrative example, the messages that the client and the server use to chat are in total control of who develops the application. Numbers do not need to be used, in short, the programmer has total freedom to choose the format of the messages, for the TCP protocol this is irrelevant.

Now, specifically speaking of your example and Node.js, the "socket" object that the "connect" event provides can be used as a unique connection identifier, considering a single server run.

2

If your system uses some form of login you probably have some unique identifier.

You can pass it from client to socket on server check and if it is valid to assign to socket object, example:

// client
var net = require('net');
var client = new net.Socket();
var clientID = "xxxxx-yyyy";
client.connect(3000, '127.0.0.1', function() {
    client.write(clientID);
});
client.on('data', function(data) {
    console.log('Recebido: ' + data);
});

// server
var net     = require("net");
var porta   = 3000;
var host    = "127.0.0.1";
var servidor = net.createServer();
servidor.listen(porta, function (socket){
    console.log(`Servidor iniciado..`);
});
servidor.on('connection', function(socket){
    socket.on('data', function(data){
        // primeira conexão? checar...
        if ( !socket.id ) {
            // na primeira conexão o id será verificado
            var clientID = data
            // checar?
            if ( checkID(clientID) ) {
                socket.id = clientID
            } else {
                // derrubar connexão?
            }
         }
    })
});

This opens the possibility of someone trying to circumvent an id on the frontend ... maybe it is more recommended to use tokens JWT to pass ids.

Now if the connection doesn’t need to follow an authentication you can simply add (generate) an id using some library "uuid", example:

// server
var net     = require("net");
var uuidv1 = require('uuid/v1'); // biblioteca uuid (v1)
var porta   = 3000;
var host    = "127.0.0.1";
var servidor = net.createServer();
servidor.listen(porta, function (socket){
    console.log(`Servidor iniciado..`);
});
servidor.on('connection', function(socket){
    socket.on('data', function(data){
        // primeira conexão? checar...
        if ( !socket.id ) {
            // a cada conexão a propriedade id será verificada
            socket.id = uuidv1();
         }
    })
});


References:

Browser other questions tagged

You are not signed in. Login or sign up in order to post.