简体   繁体   English

socket.io向房间发送消息不起作用

[英]socket.io emitting message to room does not work

Events binding for socket are moved to separate module: 套接字的事件绑定已移动到单独的模块:

exports.bind = function(socket) {
    socket.on('join', function(data) {
        socket.join(data.type);
    });
    socket.on('message', function(data) {
    global.io.sockets.in('rooma').emit('message', data);
    });
}

server.js: server.js:

var app = express();

//creating socket server
server = http.createServer(app);
io = global.io = require('socket.io').listen(server, {'log level': 3});

io.sockets.on('connection', function(socket) {
    //binding events on socket
    events.bind(socket, io);
});

The problem is, that message is never sent to the clients in 'rooma'. 问题是,该消息永远不会在“ rooma”中发送给客户端。 But if i emit it global: 但是如果我将其全局发出:

global.io.sockets.emit('message', data);

It works. 有用。 Where can be problem? 哪里有问题? I've tested the client belongs to room for sure. 我已经确定该客户属于房间。

this works when you get the initialisation of the event from the room to which you like to send your message: 当您从要向其发送消息的房间中初始化事件时,此方法将起作用:

exports.bind = function(socket) {
        socket.on('join', function(data) {
            socket.join(data.type);
        });
        socket.on('message', function(data) {
            socket.get('room', function (error, room) {
                io.sockets.in(room).emit('message', data);
            });
        });
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM