Using WebSockets With Express.js Applications

Using WebSockets With Express.js Applications

WebSockets are an essential component for building real-time applications, allowing for two-way communication between a client and a server. When paired with Express.js, a web application framework for Node.js, WebSockets can enhance the interactivity of your apps significantly. This article will guide you through using WebSockets with Express.js applications, enabling your projects to deliver real-time updates and improved user experiences.

What are WebSockets?

WebSockets are a protocol that provide full-duplex communication channels over a single TCP connection. Unlike traditional HTTP requests, which are request-response oriented, WebSockets maintain a persistent connection, allowing data to be sent and received without the overhead of HTTP headers.

Setting Up Your Express.js Application

To get started, you first need to create a basic Express.js application. If you haven’t already set up Node.js and Express, follow these steps:

  1. Install Node.js from the official website.
  2. Create a new directory for your project and navigate into it:
mkdir my-websocket-app
cd my-websocket-app
  1. Initialize a new Node.js application:
npm init -y
  1. Install the Express framework and the 'ws' library for WebSocket support:
npm install express ws

Creating a Basic WebSocket Server

Now, let’s set up the WebSocket server within your Express application. Create a file named server.js with the following code:

const express = require('express');
const http = require('http');
const WebSocket = require('ws');
const app = express();
const server = http.createServer(app);
const wss = new WebSocket.Server({ server });
wss.on('connection', (ws) => {
    console.log('New client connected');
ws.on('message', (message) => {
        console.log(`Received: ${message}`);
        // Optional: Broadcast the message to all clients
        wss.clients.forEach(client => {
            if (client.readyState === WebSocket.OPEN) {
                client.send(`Server: ${message}`);
            }
        });
    });
ws.on('close', () => {
        console.log('Client disconnected');
    });
});
app.get('/', (req, res) => {
    res.send('WebSocket server is running!');
});
const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
    console.log(`Server is listening on port ${PORT}`);
});

Testing the WebSocket Connection

To test your WebSocket server, you can use a simple HTML client. Create an index.html file in your project directory with the following content:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WebSocket Client</title>
</head>
<body>
    <h1>WebSocket Client</h1>
    <input id="message" placeholder="Type a message..."/>
    <button id="send">Send</button>
    <div id="output"></div>
<script>
        const socket = new WebSocket('ws://localhost:3000');
socket.onopen = () => {
            console.log('Connected to WebSocket server');
        };
socket.onmessage = (event) => {
            const output = document.getElementById('output');
            output.innerHTML += '<p>' + event.data + '</p>';
        };
document.getElementById('send').onclick = () => {
            const messageInput = document.getElementById('message');
            socket.send(messageInput.value);
            messageInput.value = '';
        };
    </script>
</body>
</html>

Open your terminal and run your server:

node server.js

Now, open your index.html