【问题标题】:NodeJs + Socket.io : io.to from moduleNodeJs + Socket.io:来自模块的 io.to
【发布时间】:2021-09-10 07:47:29
【问题描述】:

我正在尝试按照 Patrick Robert 的回答 How can i export socket.io into other modules in nodejs?.在我的模块中的特定房间发出消息

io.js

var sio = require('socket.io');
var io = null;

exports.io = function () {
  return io;
};

exports.initialize = function(server) {
  return io = sio(server);
};

模块.js

ioreq = require('./io')

ioreq.io().on('connection', function(socket) {
    var room_name = 2;
    socket.join(room_name);
    socket.to(room_name).emit("test",'This is a Test'); //This is working
});

function sendDataFromModule(data) { // This function don't do anything at all !
socket.to(room_name).emit("test",data);
}

sendDataFromModule('Test from function');// Not working

}

你能帮我完成它吗?

【问题讨论】:

  • 您的第二个函数不起作用,因为socket 未在该函数的范围内定义,因此您无法使用该变量。您可能需要将套接字传递给它,或者您需要切换到io.to(...).emit(...),具体取决于您真正想要做什么。

标签: javascript node.js module socket.io modularity


【解决方案1】:

制作io全局变量, 在 io.js 中

 global.io = require("socket.io")(server);

在module.js中

    //ioreq = require('./io') no need for this
    
    io.on('connection', function(socket) {
        var room_name = 2;
        socket.join(room_name);
        socket.to(room_name).emit("test",'This is a Test'); //This is working
    });
    function sendDataFromModule(data) {
io.in(room_name).emit("test",data); // change this
}

sendDataFromModule('Test from function');

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-08-29
    • 1970-01-01
    • 2023-03-24
    • 2018-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多