Address already in use with Socket.io in Express

Viewed 34

I'm trying to use websockets in my app but I'm not able to get Socket.io to connect to my server. Whenever I run the code below, I get this error:

Error: listen EADDRINUSE: address already in use :::3000

I've tried looking up some solutions, and I found that there's no other processes running on this port, so the issue has to be within the project. What could I be doing wrong here?

const express = require("express");
const mongoose = require("mongoose");
const app = express();
const { createServer } = require("http");
const httpServer = createServer(app);

const socketIO = require("socket.io")(3000, { cors: { origin: "*" } });
socketIO.on("connection", (socket) => {
    console.log("connected");
});

const port = 3000;

const startServer = () => {
    httpServer.listen(port);
    console.log(`Listening on port ${port} `);
};

mongoose
    .connect(uri)
    .then(() => startServer())
    .catch((err) => {
        console.log(err);
    });
2 Answers

If you don't supply socket.io with an http server, it will create one for you. So your code is actually creating two http servers, both trying to listen on the same port which fails with EADDRINUSE.

Instead, pass the httpServer as the first parameter to socket.io instead of a port number:

const socketIO = require("socket.io")(httpServer, { cors: { origin: "*" } });

It's happening because

const startServer = () => {
    httpServer.listen(port);
    console.log(`Listening on port ${port} `);
};

here already the address 3000 in use ... so you shouldn't pass the port:3000 into socketIO, better pass the httpServer, like :

const socketIO = require("socket.io") (httpServer,  cors: { origin: "*" } });
socketIO.on("connection", (socket) => {
    console.log("connected");
});
Related