我有一个运行良好的 Express 服务器,但现在我想在其中设置 Socket.io,
我有错误 TypeError: require(...).listen is not a function
我当前的代码(运行良好)
const app = express();
app.set("port", process.env.PORT || 5000);
app.listen(app.get("port"), () => {
console.log("Server running");
});
尝试设置 Socket.io 的代码
const port = process.env.PORT || 5000;
const server = app.listen(port, () => {
console.log("Server running");
});
const io = require("socket.io").listen(server);
有人可以帮我解决上面的错误吗?
答案 0 :(得分:1)
从 SocketIO documentation 开始,要使用 express 应用程序设置 SocketIO,应该是:
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');
});