WebSockets With Node Js and Socket.io
Hello Developers, hope you are doing good. Today we are going to look at what WebSocket is. You must have heard about real-time data during your learning process or work. Real-time data is delivered immediately after collection. There is no delay in the timeliness of the information provided. Real-time data is often used for navigation or tracking. Real-time data is often used for navigation, tracking, gaming, communications except where your user interface does not refresh frequently.
When there is communication between the two systems, we follow some protocols. The protocol is a system of rules that allow two or more entities of a communications system to transmit information via any kind of variation of a physical quantity. It defines the rules, syntax, semantics, and synchronization of communication and possible error recovery methods.
There are many different types of protocols available for communication, most used & popular is the HTTPS protocol. But if you want real-time & quick data transfer, HTTPS is not recommended.
We must go with the WebSocket protocol. It enables two-way communication between a client running untrusted code in a controlled environment to a remote host that has opted-in to communications from that code.
The major con of HTTPS for real-time data transfer is that HTTPS is unidirectional. That means, when you have to do communication it always opens the connection, does its processing, and returns with some response by closing the connection. For real-time data, it is too much processing. To avoid this, we can go with WebSockets.
The WebSocket connection is a persistent connection between a client app and the server. The server can send messages to the client and the client can respond back via the same connection. It helps to communicate the servers with clients in an async manner. The server and client can communicate and exchange data at the same time. WebSocket helps to create real-time communication between web servers and clients.
The WebSockets protocol is different from the HTTP protocol. So after the initial handshake occurs (which happens over HTTP), there is no more notion of HTTP specific things such as cookies.
So now the question is, How can we implement WebSockets?
There are many ways out of which we will go with “ socket.io ”. It is a library that enables real-time, bidirectional, and event-based communication between the browser and the server which is based on Node.js and a Javascript client library for the browser. It is the wrapper around the WebSocket API. The best part of socket.io library is -
- It supports almost all browsers (97%), that are available today
- there is no element (proxy, firewall, …) preventing WebSocket connections between the client and the server
Server-side code snippet -
const io = require(‘socket.io’)(3000);
io.on(‘connect’, socket => {
// either with send()
socket.send(‘Hello!’);
// or with emit() and custom event names
socket.emit(‘greetings’, ‘Hey!’, { ‘ms’: ‘jane’ }, Buffer.from([4, 3, 3, 1]));
// handle the event sent with socket.send()
socket.on(‘message’, (data) => {
console.log(data);
});
// handle the event sent with socket.emit()
socket.on(‘salutations’, (elem1, elem2, elem3) => {
console.log(elem1, elem2, elem3);
});
});
Client-side code snippet -
const socket = io(‘ws://localhost:3000’);
socket.on(‘connect’, () => {
// either with send()
socket.send(‘Hello!’);
// or with emit() and custom event names
socket.emit(‘salutations’, ‘Hello!’, { ‘mr’: ‘john’ }, Uint8Array.from([1, 2, 3, 4]));
});
// handle the event sent with socket.send()
socket.on(‘message’, data => {
console.log(data);
});
// handle the event sent with socket.emit()
socket.on(‘greetings’, (elem1, elem2, elem3) => {
console.log(elem1, elem2, elem3);
});
Why using ‘socket.io’ library is best -
- Better Reliability
- Auto-reconnection support
- Disconnection detection
- Binary support
- Multiplexing support
For more details what is better than official documentation! Do check the official doc at https://socket.io/