node.jsexpresssocket.io

Setting up Socket io in an Express server (Error: TypeError: require(...).listen is not a function)


I have an Express server which works well, but now I want to set up Socket.io in it, I have the error TypeError: require(...).listen is not a function

My current code (working well)

const app = express();
app.set("port", process.env.PORT || 5000);

app.listen(app.get("port"), () => {
  console.log("Server running");
});

Code trying to set up Socket.io

const port = process.env.PORT || 5000;
const server = app.listen(port, () => {
  console.log("Server running");
});
const io = require("socket.io").listen(server);

Can someone help me with the error above please ?


Solution

  • From the SocketIO documentation, to setup SocketIO with the express application, it should be:

    const express = require('express');
    const app = express();
    const http = require('http');
    const server = http.createServer(app);
    const { Server } = require("socket.io");
    const io = new Server(server);
    
    io.on('connection', (socket) => {
      console.log('a user connected');
    });