Distinguish b/w two or more TCP clients in nodejs?

五迷三道 提交于 2019-12-08 09:46:01

问题


isn't there any Unique ID or something for every client? suppose I want use this echo server to echo message received from one client to all connected clients:

var net = require('net');
var server = net.createServer();
server.on('connection', function (server_socket) {
    console.log('client connected');
    server_socket.write('hello client! Say something.');

    server_socket.pipe(server_socket);

    server_socket.on('end', function () {
        console.log('client disconnected');
    });
});

server.listen(80, 'localhost');
server.on('listen', function () {
    console.log('Listning for connections:');
});

server.on('error', function (error) {
    console.dir(error);
});

I tried Everything i knew, i.e Events like connection,request etc.


回答1:


For your purpose you do not really need of an UID, you can try to keep all the active connections in an array and broadcast any data when needed.

var connections = [];

server.on('connection', function (socket) {

    connections.push(socket);

    socket.write('SOMETHING');

    // Broadcast some message
    connections.forEach(function (connection) {
        if (connection !== socket) { // Filter connections
            connection.write('SOMETHING ELSE');
        }
    });

    // Clean up closed connections
    socket.on('close', function () {
        var index = connections.indexOf(socket); // Get socket index

        connections.splice(index, 1); // Remove the socket from the connections
    });
});



回答2:


If you would use socket.io this would be pretty easy. You would need to check the property id of the socket-object:

server.on('connection', function(socket) {
   console.log(socket.id + " connected");
});

As long as you use raw sockets you have the option to generate a id on connect, where the function generateUniqueSocketId() could return a GUID or something unique to distinguish between the connections:

server.on('connection', function(socket) {
   socket.myConnectionId = generateUniqueSocketId();
});


来源:https://stackoverflow.com/questions/31276246/distinguish-b-w-two-or-more-tcp-clients-in-nodejs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!