Home > Software design >  Socket.io client is not connecting to the server
Socket.io client is not connecting to the server

Time:04-30

I am trying to connect to the socket.io client using the following server-side code...

const express = require("express");
const { createServer } = require("HTTP");
const { Server } = require("socket.io");

const app = express();

const httpServer = createServer(app);
const io = new Server(httpServer);

io.on("connection", (socket) => {
   console.log("New user connected");
   socket.on("join_room", (room) => {
     socket.join(room);
     socket.on("message", (msg) => {
        io.to(room).emit("update_msg", msg);
     });
   });
});

const PORT = process.env.PORT || 5000;
httpServer.listen(PORT, () => {
   console.log(`Server has started on port number ${PORT}`);
});

My client-side code is as follows.

const socket = io("http://localhost:5000");
socket.emit("join_room", "Room1");

When I am running the above codes it does not print anything in the console. I am using socket.io and socket.io-client version 4.5.0 on the server-side and client-side respectively.

CodePudding user response:

const express = require("express");
const { createServer } = require("http");
const { Server } = require("socket.io");
const cors = require('cors')

const app = express();

app.use(cors())
const httpServer = createServer(app);
const io = new Server(httpServer, { cors: {
    origin: "http://localhost:4200",
    methods: ["GET", "POST"]
}});

io.on("connection", (socket) => {
  console.log("New user connected");
  socket.on("join_room", (room) => {
    socket.join(room);
    socket.on("message", (msg) => {
      io.to(room).emit("update_msg", msg);
    });
  });
});

const PORT = process.env.PORT || 5001;
httpServer.listen(PORT, () => {
  console.log(`Server has started on port number ${PORT}`);
});

Hope above code will work. Please confirm, Did you enable the CORS?, if you're trying to access from different origin.

For your'e reference, I have added the CORS while creating the HTTP Server

Ref: https://socket.io/docs/v3/handling-cors/

  • Related