插座没有广播到特定的房间

时间:2017-05-04 18:50:54

标签: node.js sockets socket.io

我正在尝试向特定房间广播一些信息:

服务器端

var io = require('socket.io')(server, { path: '/my/path' });
server.listen(8090, function () {
    console.log("Server ON.");
});

io.on('connection', function(socket){
    socket.on('room', function(room) { //set the room
        socket.join(room);
        socket.room = room;
    });
    socket.on('new message', function (data) { //receive and broadcast the msg
        socket.broadcast.to(socket.room).emit('new message', data);
    });
});

客户端

//initial client config
var socket = io(URL_SOCKET, {path: '/my/path'});
socket.emit('room', room_id);
socket.on('new message', function (data) {
    do_something(data);
});

function on_change(data){
    socket.emit('new message', data);
}

此处的问题是: socket.broadcast.to正在广播客户(通过致电on_change)向所有房间(向所有人)发送的信息。我做错了什么?

1 个答案:

答案 0 :(得分:2)

io.in(socket.room).emit('requestRes',{success:true,STATUSCODE:2000,message:"hello"}); 

尝试搜索Socket备忘单 PS:https://socket.io/docs/emit-cheatsheet/#