我试图在Express-Generator应用程序中访问Socket.io,但是获取一个空对象
我已经构建了一个使用Express Generator的Web应用程序。我希望能够通过许多不同的模块将更新发送给浏览器。
但是,我不太确定为什么我在下面提供的解决方案不起作用。
我知道exports.initialize()
函数是通过登录到控制台的,但是我遇到的错误,无法读取NULL
的属性'emit'暗示socket.io是不是被初始化的,因为它正在返回空对象。
我已经创建了一个包含以下包装器的模块:
const sio = require('socket.io')
let io = null
exports.io = function () {
return io
}
exports.initialize = function(server) {
console.log("init")
return io = sio(server)
}
我已经在app.js
文件中初始化了模块,就像这样:
// Create the http server
const server = require('http').createServer(app);
// Create the Socket IO server on
// the top of http server
const io = require('./app_modules/sockets').initialize(server)
然后,在我需要将信息发送到浏览器的模块中,我'我这样称呼插座模块:
const io = require('./sockets').io()
谁能帮助我理解为什么这不起作用,以及我能做什么来解决它?
I've built a web app with express generator. I'd like to be able to send updates to the browser from a number of different modules.
However, I'm not quite sure why the solution I've put together, below, doesn't work.
I know that the exports.initialize()
function is being called, through logging to the console, but the error I'm getting, cannot read property 'emit' of null
suggests that socket.io is not being initialized, because it's returning a null object.
I've created a module containing the below wrapper:
const sio = require('socket.io')
let io = null
exports.io = function () {
return io
}
exports.initialize = function(server) {
console.log("init")
return io = sio(server)
}
I've initialised the module in my app.js
file, like so:
// Create the http server
const server = require('http').createServer(app);
// Create the Socket IO server on
// the top of http server
const io = require('./app_modules/sockets').initialize(server)
and then, in modules where I need to send information to the browser, I'm calling the sockets module like this:
const io = require('./sockets').io()
Can anyone help me understand why this isn't working, and what I can do to fix it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
为了启动socket.io服务器,您需要调用服务器构造函数。 IO构造函数仅适用于客户端。
您的
插座
模块应该看起来像:在需要向客户发送信息的模块中,您应该使用类似的内容:
In order to start a Socket.IO server, you need to invoke the Server constructor. The io constructor is only for the client side.
Your
sockets
module should look like this:And in modules where you need to send information to the clients, you should use something like this: