本文介绍了Socket.io错误挂接到express.js的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试将socket.io和express.js挂钩:
I'm trying to hook socket.io and express.js together:
var socket = require('./socket_chat/socket.js');
var express = require('express'),
app = module.exports.app = express();
var io = require('socket.io').listen(app);
app.use(express.static(__dirname + '/app'));
io.sockets.on('connection', socket);
在此行: var io = require('socket.io').listen(app);
我遇到了一个错误:
At the line: var io = require('socket.io').listen(app);
I'm getting an error:
Error: You are trying to attach socket.io to an expressrequest handler function. Please pass a http.Server instance.
SO/google上似乎没有关于此错误的任何信息...
There doesn't seem to be anything on SO/google about this error...
推荐答案
您可以执行此操作,而无需使用 http
模块
You can do it without using http
module
app.listen返回可用于socket.io的服务器实例
app.listen return a server instance you can use for socket.io
const express = require('express');
const app = express();
const server = app.listen(port, () => {
console.log("Listening on port: " + port);
});
const io = require('socket.io')(server);
这篇关于Socket.io错误挂接到express.js的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!