Search code examples
node.jswebsocketmessagews

How to specify message destination on the nodejs websocket?


I want to send messages from nodejs backend to the specified websocket channel. So I want to implement/use similar function like convertAndSend function on the spring SimpMessagingTemplate.

I try to implement this with ws lib, but the send function only has two parameter: message & callback and I cannot specify the message destination. Here is a brief example from backend code:

const wss = new WebSocket.Server({
    port: 8081,
    server: app,
    path: '/ws',
    /*...*/
});
/*...*/
wss.send(`chat-room/${roomId}`, JSON.stringify(message)); // I want to this

And here is a brief frontend code that works well:

/*...*/
this.rxStomp.configure({
  brokerURL: 'ws://localhost:8081/ws',
  /*...*/
});
this.rxStomp.activate();
/*...*/
return this.rxStomp.watch(`chat-room/${roomId}`);

So my question is: it is possible to specify message destination with ws or other libs on the nodejs? If yes then how?


Solution

  • I have not used 'Convert and send' or the 'Web Socket' module ( I use socket.io personally ) but the concept should be the same.

    The basic flow is

    1. User connects to socket server ( gets a socket ID assigned to them )

    2. On an action, lets say 'joinroom' from the client app you execute a 'emit' command to the websocket server (this is socket.io syntax) eg

       socket.emit('joinRoom',roomID,otherparams)
      

    In the sample above, we are 'emitting' a request to our 'socket' server, in the above example 'socket' is the namespace for our socket connection, so socket.emit send the request to the socket server.

    1. Our socket server has code to 'listen' for requests to 'joinRoom' using the 'on' syntax eg

      socket.on('joinRoom',(roomID,otherparams)=>{
      //perform action, eg. query DB for room chats etc
      // once action is done, emit back to user
         socket.in(roomID).emit(data)
      }) 
      

    In the above code, we have an 'on' event that is the 'listener' on the socket server, this will listen for 'emits' to this action, so from the client we ran an 'emit' to the socket server, the socket server found the action (on event) 'joinRoom' and ran the code, after the code was successful it then finds all users 'in' the room (roomID that was passed to the emit) and sends it to all 'sockets' that are 'in' that room

    1. On your client, you too have 'on' listeners, so when the socket server 'emits' to the client(s) they are listening for those specific commands. Because the 'socket.in' only 'emits' to clients who are 'in' the room only those users get the new payload from the server

    You app will continue in this fashion, emits and on events. This is the basic flow and can be built out for 1 to 1 chats, group chats etc