Node.js: how to use WebSocket

Node.js: how to use WebSocket

In this article, we will explore how to use WebSockets in Node.js, focusing on a popular library called "ws" (WebSocket).

WebSockets are a fundamental technology for developing real-time web applications. Unlike traditional HTTP requests, WebSockets allow persistent two-way communication between the client and the server. This feature makes them ideal for applications that require real-time updates, such as chat, online gaming and real-time monitoring.

Node.js, known for its efficiency in asynchronous I/O, is an ideal environment for developing WebSocket applications. In this article, we will explore how to use WebSockets in Node.js, focusing on a popular library called "ws" (WebSocket).

Installing the WebSocket library

Before starting, you need to install the ws library in your Node.js project. You can do this using npm (Node Package Manager) with the following command:


npm install ws

Creating a WebSocket server

To create a WebSocket server with Node.js, you need to set up a standard HTTP server and add WebSocket support. Here is an example of how to do this using the http module and the ws: library.


const http = require('http');
const WebSocket = require('ws');

// Creation of the HTTP server
const server = http.createServer((req, res) => {
   res.writeHead(200, { 'Content-Type': 'text/plain' });
   res.end('WebSocket Server');
});

// Creating the WebSocket server
const wss = new WebSocket.Server({ server });

// Management of WebSocket connections
wss.on('connection', (ws) => {
   console.log('New WebSocket connection.');

   // Management of received messages
   ws.on('message', (message) => {
     console.log(`Message received: ${message}`);
   });

   // Sending a message to the client
   ws.send('Welcome to real-time chat!');
});

// Starting the server on port 3000
server.listen(3000, () => {
   console.log('Server listening on port 3000.');
});

In this example, we are creating a basic HTTP server and a WebSocket server using the ws library. When a client connects to the WebSocket server, a welcome message is sent, and the server is ready to receive and send messages.

Creating a WebSocket client

Now that the server is configured, we can develop a WebSocket client to interact with it. Here is an example of how to do it using the ws library also on the client side:


const WebSocket = require('ws');

// Creating a WebSocket object
const ws = new WebSocket('ws://localhost:3000');

// Handling connection events
ws.on('open', () => {
   console.log('Connection established.');

   // Sending a message to the server
   ws.send('Hi, I\'m the client!');
});

// Management of messages received from the server
ws.on('message', (message) => {
   console.log(`Message received from server: ${message}`);
});

// Management of closing events
ws.on('close', () => {
   console.log('Connection closed.');
});

In this example, we are creating a WebSocket object and connecting to the previously created WebSocket server. Once the connection is established, we send a message to the server and manage the received messages.

Conclusions

Using WebSockets in Node.js opens the door to a wide range of possibilities for developing real-time applications. The ws library greatly simplifies the management of WebSocket connections on both the server and client sides. By further exploring the features offered by this library, you can implement real-time chat, interactive games, and many other engaging applications. With its asynchronous nature and broad community support, Node.js remains an ideal environment for developing responsive and performant WebSocket-based web applications.