Express 服务器和 socket.io 不在同一个端口工作

Express server and socket.io not working in same port

无法在代码中找到任何问题##

If I put any port number instead of server it's working but why didn't it's working with socket server anyone explain I tried some solution but none of them work I want to run socket.io and express on same port number

const express = require('express');
const cors = require("cors");
const socketIO = require('socket.io');
const http = require('http');
const app = express();
const server = http.createServer(app);
const passport = require("passport");
const authRoute = require('./routes/auth');
const userRoute = require('./routes/user');
const PORT = process.env.PORT || 9000;
const db = require('./config/mongoose');
app.use(express.json());
app.use(cors());

app.use(passport.initialize());
require("./config/passport")(passport);

app.use(express.json());
app.use("/api/auth", authRoute);
app.use("/api/user", passport.authenticate('jwt', { session: false }),userRoute);

if(process.env.NODE_ENV === 'production')
{
    app.use(express.static('client/build'))
}

如果我将服务器切换到任何端口号就可以了

const io = socketIO(server, {
    cors: {
        origin: '*',
    }
});
let state = {};
io.on("connection", (socket) => {
    const { id } = socket.client;
    socket.on('disconnect', function () {
        console.log('socket disconnected!');
    });
    socket.on('join_room', function (data) {
        console.log('joining request rec.', data);

        socket.join(data.room);

        io.in(data.room).emit('user_joined', data);
    });
    socket.on('send_code', function (data) {
        io.in(data.room).emit('receive_code', data);
    });
});

app.listen(PORT, function (err) {
    if(err){
        console.log(err);
        return;
    }
    console.log(`Server is up and running on port: ${PORT}`);
});

http.createServer(app)app.listen() 不兼容,因为它们都试图做同样的事情。如果您查看 app.listen() 的源代码,您将看到:

app.listen = function listen() {
  var server = http.createServer(this);
  return server.listen.apply(server, arguments);
};

因此,它正在创建一个不同的服务器对象。你最终得到两个,第一个永远不会开始,所以当你把它给 socket.io 时,它永远不会起作用。

相反,删除这个:

const server = http.createServer(app);

并且,改用这个:

const server = app.listen(PORT, function (err) { ...});

这样,您的 server 变量将包含唯一的服务器对象,它实际上是 运行.


或者,您可以删除 app.listen(),然后将其添加到原处:

server.listen(PORT, ...);

大意是你想要这双:

const server = http.createServer(app);
server.listen(PORT, ...);

或者,只是这样:

const server = app.listen(PORT, ...);

您不能同时使用两者。无论哪种方式,server 对象将代表实际上是 运行 的服务器,并将与 socket.io.

一起工作