【问题标题】:Socket.io global sending Function - Node.jsSocket.io 全局发送函数 - Node.js
【发布时间】:2020-01-27 03:44:54
【问题描述】:

我构建了一个简单的 node.js / socket.io 应用程序。 我需要一个模块来发出事件,该模块可以通过其他模块访问,这样我就可以在有新的数据库条目时发送套接字消息。

类似这样的:

function sendWebsocketEvent (whereToSend, EventName, Payload) {
    io.in(whereToSend).emit(EventName, Payload)
  }

我该如何处理?

我试过了:

-- app.js--

// Websockets
var http = require('http').createServer(app)
var io = require('socket.io')(http)
http.listen(3000, function () {
  console.log('listening on Port *:3000')
})
require('./WebSockets/socketInit')(io)

-- socketInit.js--

module.exports = (ioInput) => {
  const io = ioInput
  return io
}

-- sendSockets.js--

const io = require('./socketInit')
module.exports = {
  sendWebsocketEvent (whereToSend, EventName, Payload) {
    io.in(whereToSend).emit(EventName, Payload)
  }
}

我试图在另一个模块中调用这个函数:

const sendSockets = require('../WebSockets/sendSockets')
.
.
.
 sendSockets.sendWebsocketEvent('user', 'databaseUpdate', 'dataToSend')
 .
 .
 .

但这不起作用。

还有其他方法可以完成这项工作吗?

  • 克里斯

【问题讨论】:

标签: javascript node.js socket.io


【解决方案1】:

内部Server.js

const express = require('express');
const app = express();
const server = require('http').createServer(app)
const io = socket.listen(server);
global.io = io;

const port = process.env.PORT || 5500;
server.listen(port, () => console.log(`%s ? Server is listening on port ${port}`, chalk.green('✓')));

// socket io connection 
let interval;
io.on("connection", socket => {
    console.log("New client connected");
    if (interval) {
        clearInterval(interval);
    }
});

然后像那样在你想要的地方发射

global.io.emit('EventName', data);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-01-19
    • 1970-01-01
    • 2014-03-03
    • 2017-09-22
    • 1970-01-01
    • 1970-01-01
    • 2018-08-10
    • 2023-03-27
    相关资源
    最近更新 更多