Currently I am experimenting with a data-intensive application built using web technologies. The biggest challenge is to reflect in UI real-time changes to the data stored on the server.
I implemented long polling where the client polls the server, requesting new information. The server receives the request from the client, keeps it open and responds once new data is available. This implementation is suitable for small projects but can become a problem for high scalable applications with numerous clients and frequent changes to data.
The second approach is to implement bidirectional communication between server and client and allow the server to push notification to the client only when data changes. In this context one can use WebSocket-s.
WebSocket (https://en.wikipedia.org/wiki/WebSocket) is a computer communications protocol, providing full-duplex communication channels over a single TCP.
A convenient abstraction around the WebSocket protocol is Socket.IO library/module (https://socket.io/).
Socket.IO enables real-time, bidirectional and event-based communication. It works on every platform, browser or device, focusing equally on reliability and speed.
In the context of Node.js, Socket.IO provides a consistent interface both in the browser and on the server for performing bidirectional communications.
Socket.IO provides an abstraction over the various methods used to maintain an active connection between a browser and a server. It will use WebSocket where the protocol is supported, and will transparently fall back to several other techniques in cases where WebSocket is not yet supported or the firewall introduces some limitations.
Below you can find a working example for demonstrating the bidirectional communication between Client and Server using Socket.IO.
The code is available also on Git: https://github.com/luckpp/socket-io-demo.
Open the Terminal and create the project structure:
$mkdir socket-io-demo $cd socket-io-demo $npm init
Install the Socket.IO module:
$npm install socket.io
Add the server side code:
Add the client code:
Start the server:
Open the Browser and navigate to this URL: http://localhost:4200/