我的代码如下所示:
const express = require('express');
const app = express();
const io = require('socket.io')(app);
io.on('connection',(socket) =>{
console.log('a user is connected');
});
app.listen(port, () => {
console.log('server started');
});
运行上面的代码时,出现以下错误:
Error: You are trying to attach socket.io to an express request handler function. Please pass a http.Server instance.
那么,有什么办法可以只使用Express模块运行socket.io?
答案 0 :(得分:1)
不。从3.0开始,快速应用程序已成为您传递给http或http Server实例的请求处理程序功能。您需要将服务器传递给socket.io,而不是快速应用程序函数。另外,请确保在服务器而非应用程序上调用.listen。
var app = require('express')();
var server = require('http').createServer(app);
var io = require('socket.io')(server); //listen server not app
io.on('connection', function(){ /* … */ });
server.listen(3000);