Sending message to a specific connected users using webSocket?
Asked 07 September, 2021
Viewed 1.5K times
  • 49
Votes

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?

5 Answer