How to Implement WebSocket Compression in Node.js

How to Implement WebSocket Compression in Node.js

WebSocket is a communication protocol that allows for full-duplex communication channels over a single TCP connection. It provides a way for web applications to maintain an open connection with the server, which can be efficient for real-time applications. However, when dealing with larger messages or frequent data transfers, performance can become an issue. To address this, implementing WebSocket compression can significantly reduce the amount of data transmitted over the network. Here’s how to implement WebSocket compression in Node.js.

1. Prerequisites

Before you start, ensure you have the following:

  • Node.js installed on your machine.
  • A basic understanding of WebSocket and how to set it up in a Node.js application.
  • Familiarity with the ws library, which will be utilized for WebSocket implementation.

2. Installing Required Packages

First, you need to install the ws library, which provides an easy-to-use WebSocket implementation for Node.js. You can add ws to your project using npm:

npm install ws

If you want to enable compression, you will also need the ws-compression package:

npm install ws-compression

3. Setting Up the WebSocket Server

To set up a WebSocket server with compression, create a new JavaScript file, say server.js, and include the following code:


const WebSocket = require('ws');
const WebSocketServer = WebSocket.Server;
const Compression = require('ws-compression');
const server = new WebSocketServer({ port: 8080, perMessageDeflate: true });
server.on('connection', (socket) => {
    console.log('A new client connected');
// Handling incoming messages
    socket.on('message', (message) => {
        console.log(`Received: ${message}`);
        socket.send(`Echo: ${message}`); // Sending the same message back
    });
socket.on('close', () => {
        console.log('Client disconnected');
    });
});
console.log('WebSocket server is running on ws://localhost:8080');

In this code, we create a WebSocket server that listens on port 8080 and enables message deflation, which allows for compression.

4. Enabling Compression

Compression is handled automatically by the ws library with the perMessageDeflate option. This option allows the server to compress messages before sending them to the client and decompress messages received from the client. Here’s a more detailed look at the configurations:


const server = new WebSocketServer({
    port: 8080,
    perMessageDeflate: {
        threshold: 1024 // Only compress messages larger than this size
    }
});

This configuration compresses messages larger than 1KB, ensuring that small messages are sent uncompressed, which can be more efficient.

5. Creating the Client

Now, let’s create a simple client to test the WebSocket server. You can add the following HTML code in a file named index.html:





    
    
    WebSocket Client


    


Open this HTML file in a web browser, and it will connect to your WebSocket server. You will see connection logs in the console.

6. Testing Compression

To test if the compression is working, you can send larger messages and monitor the data size transmitted. Use browser tools or consume network traffic