我试图在Express-Generator应用程序中访问Socket.io,但是获取一个空对象

发布于 2025-01-23 11:09:35 字数 885 浏览 4 评论 0原文

我已经构建了一个使用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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

久伴你 2025-01-30 11:09:35

为了启动socket.io服务器,您需要调用服务器构造函数。 IO构造函数仅适用于客户端。

您的插座模块应该看起来像:

const sio = require('socket.io')
let io = null

exports.io = io

exports.initialize = function(server) {
  io = new sio.Server(server);

  return io
}

在需要向客户发送信息的模块中,您应该使用类似的内容:

const io = require('./sockets').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:

const sio = require('socket.io')
let io = null

exports.io = io

exports.initialize = function(server) {
  io = new sio.Server(server);

  return io
}

And in modules where you need to send information to the clients, you should use something like this:

const io = require('./sockets').io
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文