Ad

How To Connect Multiple Socket Clients Nodejs

- 1 answer

Scenario is i have a server where socket(1) runs i have one more server where socket(2) client connects to socket(1)

I have one browser socket which connects to socket(1)

Idea is to do request from browser and bring data from socket(2) server

Not sure how to difference between socket clients as all the sockets are similar to socket(1)

Ideally there will be multiple browser sockets and multiple socket(2) clients

Browser sockets can make request to any of the socket(2) clients

How to implement it using nodejs socket.io

Server

socket.on('action', (action) => {
     if(action.type === 'server/hello'){
       io.sockets.emit('broadcast',{ description: clients + ' clients connected!'});
       console.log('Got hello data!', action.data);
     }
   });

Browser client

 var socket = io.connect('localhost:3000', {reconnect: true});
socket.on('connect', function(data) {
    socket.emit('joined', 'Hello World from client this is client plxx');
});
socket.on('response2', function(data) {
    console.log("got it ", data);
    $('#messages').append($('<li>').text(JSON.stringify(data)));
});

Server client

var io = require('socket.io-client');
var socket = io.connect('http://localhost:3000', {reconnect: true});

socket.on('broadcast', function (t) {
    socket.emit("data", {data: 32})
    console.log('broadcast! my host is est');
});

i should be able to communicate between socket clients

Ad

Answer

What I understood from your question is: you need to differentiate between sockets from different clients.

To solve that I would suggest simply emitting the socket source from the client on connect. And on the server split the sockets into two lists.

Example:

Server

const BROWSER_CLIENTS = {};
const SERVER_CLIENTS = {};
io.on("connection", socket => {
    socket.on("source", payload => {
        if (payload == "browser")
            BROWSER_CLIENTS[socket.id] = socket;
        else if (payload == "server")
            SERVER_CLIENTS[socket.id] = socket;
    });
    socket.on("disconnect", () => {
        delete BROWSER_CLIENTS[socket.id];
        delete SERVER_CLIENTS[socket.id];
    });
});

Browser Client

socket.on("connect", () => {
    socket.emit("source", "browser");
});

Server Client

socket.on("connect", () => {
    socket.emit("source", "server");
});

Now when you receive an event you can detect from which source it originated. And if you need to send to all sockets of one type of clients you can simply do this:

Server

for (let i in BROWSER_CLIENTS)
    BROWSER_CLIENTS[i].emit("Hello Browsers")

for (let i in SERVER_CLIENTS)
    SERVER_CLIENTS[i].emit("Hello Servers")

EDIT: I found this link and thought you could make use of it. Socket.io Rooms

Ad
source: stackoverflow.com
Ad