node.jsexpresswebsocketws

Do I need to use "import { createServer } from 'http';" to use websockets / ws library with express in node?


So I had a working express server that I wanted to add websockets functionality to it, this is the code that should have worked

import express from "express";
import { WebSocketServer } from 'ws';
const app = express();
const port = 80;

const wss = new WebSocketServer({ server:app });
wss.on('connection', function connection(ws) {
  ws.on('message', function message(data) {
    console.log('received: %s', data);
  });
});
app.listen(port, function () {
  console.log("Server listening on port: " + port);
});

the above did not work, what worked is this:

import { createServer } from 'http';
import express from "express";
import { WebSocketServer } from 'ws';
const app = express();
const port = 80;
const server = createServer(app)

const wss = new WebSocketServer({ server:server });
wss.on('connection', function connection(ws) {
  ws.on('message', function message(data) {
    console.log('received: %s', data);
  });
});
server.listen(port, function () {
  console.log("Server listening on port: " + port);
});

so is my conclusion correct that I need to import { createServer } from 'http' to make the code works?


Solution

  • Short answer - Yes. If you're using it with the Express you have to.

    Express is a web server framework built on top of Node.js's HTTP server, it does not expose the server instance directly. Therefore, to use WebSockets with Express, you've to create an HTTP server yourself.

    const server = createServer(app);
    

    Without the above line, the server won't run WS connection.