shubham katariya
shubham katariya

Reputation: 11

Persist websocket connection object across the multiple server

I am using a websocket library on server for establishing socket connection.

https://github.com/websockets/ws

I have a more than one server in cluster, I want to know how can I use same socket connection object on another server in cluster.

And also I want to know what is the best option for webchat implementation native websocket or socket.io

Upvotes: 1

Views: 1594

Answers (1)

jfriend00
jfriend00

Reputation: 707986

You cannot use the same actual socket object across multiple servers. The socket object represents a socket connection between a client and one physical server process. It is possible to build a virtual socket object that would know what server its connection is on, send that server a message to then send out over the actual socket from that other server.

The socket.io/redis adapter is one such virtual ways of doing this. You set up a node.js cluster and you use the redis adapter with socket.io. It uses a central redis-based store to keep track of which serve process each physical connection is one. Then, when you want to send a message to a particular client from any of the server processes, you send that message through socket.io and it looks up for you in the redis database where that socket is connected, contacts that actual server and asks it to send the message to that particular client over the socket.io connection that is currently present on that other server process. Similarly, you can broadcast to groups of sockets and it will do all the work under the covers of making sure the message gets to the clients no matter which actual server they are connected to.

You could surely build something similar yourself for plain webSocket connections and others have built pieces of it. I'm not familiar enough with what exists out there in the wild to offer any recommendations for a plain webSocket. There plenty of articles on scaling webSocket servers horizontally which you can find with Google and read to get started if you want to do it with a plain webSocket.

Upvotes: 4

Related Questions