Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do i send a message to a specific user in ws library?

I'm exploring different websocket library for self-learning and I found that this library is really amazing ws-node. I'm building a basic 1 on 1 chat in ws-node library

My question is what is the equivalent of socket.io function which is socket.to().emit() in ws? because i want to send a message to a specific user.

Frontend - socket.io

socket.emit("message", { message: "my name is dragon", userID: "123"});

Serverside - socket.io

// listening on Message sent by users
socket.on("message", (data) => {
    // Send to a specific user for 1 on 1 chat
    socket.to(data.userID).emit(data.message);
});

WS - backend

const express = require('express');
const http =  require('http');
const WebSocket = require('ws');
const express = require('express');
const http =  require('http');
const WebSocket = require('ws');

const app = express();

const server = http.createServer(app);

const wss = new WebSocket.Server({ server });
wss.on('connection', (ws) => {

    ws.on('message', (data) => {   
        \\ I can't give it a extra parameter so that I can listen on the client side, and how do I send to a specific user?
        ws.send(`Hello, you sent -> ${data.message}`);
    });
});
like image 463
airsoftFreak Avatar asked Nov 07 '22 04:11

airsoftFreak


1 Answers

Honestly, the best approach is to abstract away the WebSocket using a pub/sub service.

The issue with client<=(server)=>client communication using WebSockets is that client connections are specific to the process (and machine) that "owns" the connection.

The moment your application expands beyond a single process (i.e., due to horizontal scaling requirements), the WebSocket "collection" becomes irrelevant at best. The array / dictionary in which you stored all your WebSocket connections now only stores some of the connections.

To correct approach would be to use a pub/sub approach, perhaps using something similar to Redis.

This allows every User to "subscribe" to a private "channel" (or "subject"). Users can subscribe to more than one "channel" (for example, a global notification channel).

To send a private message, another user "publishes" to that private "channel" - and that's it.

The pub/sub service routes the messages from the "channels" to the correct subscribers - even if they don't share the same process or the same machine.

This allows a client connected to your server in Germany to send a private message to a client connected to your server in Oregon (USA) without anyone being worried about the identity of the server / process that "owns" the connection.

like image 77
Myst Avatar answered Nov 14 '22 05:11

Myst