Deepak Rana

WEBSOCKETS WITH NODEJS

By Deepak Rana

Last updated cal_iconMarch 15, 2023

WHAT ARE WEBSOCKETS?

WebSockets is a communication protocol that enables real-time bidirectional communication between a client and a server. It is built on top of the HTTP protocol, but unlike HTTP, which is stateless, WebSockets maintain a persistent connection between the client and the server, allowing for low-latency, real-time data transfer.

WebSockets work by establishing a handshake between the client and the server. This handshake consists of an HTTP request from the client to the server, followed by an HTTP response from the server to the client. If the handshake is successful, a persistent connection is established between the two parties, and they can exchange data in both directions.

One of the benefits of WebSockets is that they use a single connection, which reduces the overhead of establishing multiple connections. Additionally, WebSockets are more efficient than traditional polling mechanisms because they allow for data to be pushed from the server to the client in real-time, rather than requiring the client to request updates at regular intervals.

WebSockets can be used for a variety of applications, such as chat applications, online gaming, and real-time collaboration tools. They are also useful for streaming media, as they can be used to deliver audio and video content in real-time.

There are several libraries and frameworks that can be used to implement WebSockets in web applications, including Socket.IO, SockJS, and ws. These libraries provide an abstraction over the low-level WebSockets API, making it easier to implement real-time features in web applications.

 

WHY WE NEEDED WEBSOCKETS?

The usage of WebSockets arose as a solution to the limitations of traditional client-server communication protocols, such as HTTP. In traditional client-server communication, the client sends a request to the server and the server responds with the requested data. This works well for many types of applications, but it has limitations when it comes to real-time communication.

One limitation of traditional client-server communication is that the client has to initiate the communication, which can lead to delays and increased server load. This is especially problematic in applications that require real-time communication, such as chat applications or online games, where even a slight delay can negatively impact the user experience.

Another limitation of traditional client-server communication is that it requires a new connection to be established for each request/response cycle. This can be inefficient, especially when dealing with small, frequent updates. For example, in a real-time stock market application, it may be necessary to update the stock prices multiple times per second, which can result in a high volume of requests and increased server load.

WebSockets address these limitations by establishing a persistent, bidirectional communication channel between the client and the server. This allows data to be sent in both directions without the need for the client to initiate each communication cycle. Additionally, the persistent connection reduces the overhead of establishing new connections for each update, making it more efficient for applications that require frequent updates.

Overall, the usage of WebSockets arose as a solution to the limitations of traditional client-server communication, and it has proven to be a powerful tool for building real-time web applications.

LET’S IMPLEMENT 

To get started with WebSockets in Node.js, we will need to install the ws module. This module provides a WebSocket server and client implementation that we can use to create a real-time communication channel between a client and a server.

To install the ws module, we can use the following command:

const WebSocket = require(‘ws’);

const server = new WebSocket.Server({ port: 8080 });

server.on(‘connection’, (socket) => {
  console.log(‘Client connected’);

  socket.on(‘message’, (message) => {
    console.log(`Received message: ${message}`);

    // Dispatch a response back to the client
    socket.send(`You said: ${message}`);
  });

  socket.on(‘close’, () => {

console.log(‘Client disconnected’);
  });
});

In this example, we create a new WebSocket.Server instance on port 8080. We then listen for the connection event, which is triggered when a client connects to the server. When a client connects, we log a message to the console and attach event listeners to the socket object.

The message event listener is triggered when a client sends a message to the server. We log the message to the console and send a response back to the client using the send method on the socket object.

The close event listener is triggered when the client disconnects from the server. We log a message to the console to indicate that the client has disconnected.

Now that we have created a WebSocket server, we can create a client to connect to the server. Here is an example:

javascript

const WebSocket = require(‘ws’);

const socket = new WebSocket(‘ws://localhost:8080’);

socket.on(‘open’, () => {
  console.log(‘Connected to server’);

  // Send a message to the server
  socket.send(‘Hello, server!’);
});

socket.on(‘message’, (message) => {
  console.log(`Received message: ${message}`);
});

socket.on(‘close’, () => {
  console.log(‘Disconnected from server’);
});

In this example, we create a new WebSocket instance that connects to the server on port 8080. We listen for the open event, which is triggered when the connection is established. When the connection is established, we log a message to the console and send a message to the server using the send method on the socket object.

We also attach an event listener to the message event, which is triggered when the server sends a message back to the client. We log the message to the console.

Finally, we attach an event listener to the close event, which is triggered when the connection to the server is closed. We log a message to the console to indicate that the connection has been closed.

 

CONCLUSION

In conclusion, WebSockets are a powerful technology that allow real-time communication between a client and a server. In Node.js, we can use the ws module to create a WebSocket server and client. With WebSockets, we can create real-time applications that provide a better user experience and increased performance.

Get In Touch

How Can We Help ?

We make your product happen. Our dynamic, robust and scalable solutions help you drive value at the greatest speed in the market

We specialize in full-stack software & web app development with a key focus on JavaScript, Kubernetes and Microservices
Your path to drive 360° value starts from here
Enhance your market & geographic reach by partnering with NodeXperts