问题
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