Sending message to a specific connected users using webSocket?

Royi Namir picture Royi Namir · Apr 29, 2013 · Viewed 85.3k times · Source

I wrote a code for broadcasting a message to all users:

// websocket and http servers
var webSocketServer = require('websocket').server;

...
...
var clients = [ ];

var server = http.createServer(function(request, response) {
    // Not important for us. We're writing WebSocket server, not HTTP server
});
server.listen(webSocketsServerPort, function() {
  ...
});

var wsServer = new webSocketServer({
    // WebSocket server is tied to a HTTP server. 
    httpServer: server
});

// This callback function is called every time someone
// tries to connect to the WebSocket server
wsServer.on('request', function(request) {
...
var connection = request.accept(null, request.origin); 
var index = clients.push(connection) - 1;
...

Please notice:

  • I don't have any user reference but only a connection .
  • All users connection are stored in an array.

Goal: Let's say that the Node.js server wants to send a message to a specific client (John). How would the NodeJs server know which connection John has? The Node.js server doesn't even know John. all it sees is the connections.

So, I believe that now, I shouldn't store users only by their connection, instead, I need to store an object, which will contain the userId and the connection object.

Idea:

  • When the page finishes loading (DOM ready) - establish a connection to the Node.js server.

  • When the Node.js server accept a connection - generate a unique string and send it to the client browser. Store the user connection and the unique string in an object. e.g. {UserID:"6", value: {connectionObject}}

  • At client side, when this message arrives - store it in a hidden field or cookie. (for future requests to the NodeJs server )


When the server wants to send a message to John:

  • Find john's UserID in the dictionary and send a message by the corresponding connection.

  • please notice there is no asp.net server code invloced here (in the message mechanism). only NodeJs .*

Question:

Is this the right way to go?

Answer

freakish picture freakish · May 1, 2013

This is not only the right way to go, but the only way. Basically each connection needs a unique ID. Otherwise you won't be able to identify them, it's as simple as that.

Now how you will represent it it's a different thing. Making an object with id and connection properties is a good way to do that ( I would definitely go for it ). You could also attach the id directly to connection object.

Also remember that if you want communication between users, then you have to send target user's ID as well, i.e. when user A wants to send a message to user B, then obviously A has to know the ID of B.