嘿,socket.io和房间有问题。我想做的是选择一个随机的用户,该用户连接到套接字,并且只向该用户写一条消息。我在服务器端的代码是。
functionx(userid, io.sockets.in(userid));
在这行代码中,我使用参数userid和具有userid room的socket触发functionx 这是功能
function functionx(user, socket){
console.log(socket.rooms[0]);-->gives the correct user id i put in io.sockets.in(userid)
//i tried socket.emit / sockets.in(socket.rooms[0])... and many more and nothing seems to work
socket.to(socket.rooms).broadcast.emit('message', {
type: 'msg',
msg: 'hello you'
});
在客户端,我有此代码。
SOCKET.on('message', function(msg) {
onMessage(msg);
});
function onMessage(msg) {
if (msg.type == 'msg')
{
alert(msg.msg);
}
}
但是我无法上班,也不知道为什么?我尝试了socket.io cheatcheet的每种方法,所以也许有人在这里有了一个主意,因为我的工作到此为止。
---------------------编辑------------------------- ------ 我设法使它工作。我只是说每个连接到套接字io的用户加入一个房间,该房间从数据库中有用户ID,并且可以按我的意愿工作。
服务器端:
socket.join(userid);
并发出一个特定的套接字我说:
io.to(userid).emit('message', {
type: 'hello',
msg: 'only you'
});
但是我知道过去我可以在不额外加入房间的情况下开始工作,但也许不能使用新版本的socket.io