Home > Software engineering >  Sending JSON to all online clients without them making a request. [NodeJS]
Sending JSON to all online clients without them making a request. [NodeJS]

Time:08-29

I'm building a website, and one of the features is a public chat that anyone online can use. When a message is entered it is sent to the server and then saved to a SQL database. How could I relay this information to all the online clients without them making a request to the server? I've thought about having all clients make a request to the server every 500ms or so but I feel that would be incredibly inefficient. Any suggestions?

CodePudding user response:

What you're looking for is typically called "server push" where the server can unilaterally send data to the client without the client having to "poll" or repeatedly ask for new info.

The two general technologies for server push these days are webSockets and server-sent events (SSE). In both cases, the client initiates a connection to the server and that connection is held open so that the server can send data to the client whenever it wants to without the client having to specifically poll for that data.

A webSocket is a full, two-way data channel. Either client or server can send data in either direction.

SSE is a one-way channel, the server can send data to a listening client.

You can see these articles on comparing the pros/cons of each.

WebSockets vs Server-Sent Events - ably.com

Server-sent events vs. WebSockets - logrocket.com

Difference between server sent events and Websockets in HTML5 - geeksforgeeks.org

And, there are dozens of other articles here.

You may also want to be aware of socket.io which is a widely used layer built on top of webSockets that adds more features than either of these have (a named message layer, auto-reconnect, message acknowledgement, direct message response, built-in JSON support, etc...).

Any of these can do what you're asking for. Which of these to choose really depends upon the details of your requirements.

CodePudding user response:

Try making a WebSocket server. There is ws package for Node.js, and alternatively socket.io. However if your client is a web client, you can use socket.io for easy-use and setup.

  • Related