Home   tech  

Can we create a WebSocket server using Express.js

You can create a WebSocket server using Express.js, but it's important to note that Express.js itself is designed primarily for HTTP server functionality. To handle WebSocket connections in an application that uses Express.js, you would typically integrate a library that supports WebSockets, such as ws or socket.io, with your Express.js server. socket.io is particularly popular because it provides high-level abstractions for real-time bi-directional event-based communication and falls back to HTTP long polling if WebSockets are not available, making it more versatile.

Creating a WebSocket Server with Express.js and ws:

Here's a basic example of how you might set up a WebSocket server alongside an Express.js HTTP server using the ws library:

  1. Install Express and ws: First, you need to install Express and ws if you haven't already:

    npm install express ws
    
  2. Create an HTTP Server with Express.js:

    const express = require('express');
    const http = require('http');
    const WebSocket = require('ws');
    
    const app = express();
    const server = http.createServer(app);
    
    // Serve some HTTP content
    app.get('/', (req, res) => res.send('Hello, World!'));
    
    const wss = new WebSocket.Server({ server });
    
    wss.on('connection', function connection(ws) {
      ws.on('message', function incoming(message) {
        console.log('received: %s', message);
      });
    
      ws.send('something');
    });
    
    server.listen(3000, function listening() {
      console.log('Listening on %d', server.address().port);
    });
    

In this setup, Express handles the HTTP requests, while the ws library is used to establish a WebSocket server that shares the same underlying HTTP server. This allows you to serve both HTTP and WebSocket traffic on the same port (in this case, port 3000).

How is a WebSocket Server Different Than an HTTP Server?

Published on: Feb 28, 2024, 01:25 AM  
 

Comments

Add your comment