我想发送消息到特定房间(房间里的所有客户),我已经搜索了很多并尝试了这些选项:
io.in(socket.RoomId).emit('Test');
io.to(socket.RoomId).emit('Test');
io.sockets.in(socket.RoomId).emit('Test');
我想发送服务器,所以不使用房间里现有的套接字。但是因为我找不到办法,所以我尝试了以下方法:
this.ListOfSockets[0].to(RoomId).emit('Test');
这不起作用,所以我试着像这样向插座本身发射:
this.ListOfSockets[0].emit('Test');
这就像我预期的那样工作。
我做错了什么?为什么我不能作为服务器发送到特定房间的所有客户端?
更新2: 为li X添加更多代码
io.on('connection', function(socket){
console.log('client connected');
playerCount++;
//For testing purposes I give player random generated string using: var shortid = require('shortid');
socket.id = shortid.generate();
console.log('id of this socket is:' + socket.id);
//When client decides to play the game and want's to join a random room
socket.on('JoinRoom', function ()
{
//Checks if there exist an open room
if(OpenRoom.length > 0)
{
//Joins first room in openroom list
socket.join(OpenRoom[0].RID);
socket.RoomId = OpenRoom[0].RID;
//Joinedroom lets player open the next scene in my game
socket.emit('JoinedRoom');
//Joinedroom is a function that sends information to the socket about the room and the state of the game,
//adding the the player to room etc.
JoinedRoom(socket.id, OpenRoom[0].RID, socket);
}
else
{
//If there is no open room, it creates a new room with new id.
OpenRoom.push({ RID:shortid.generate(), TimeOutID: null });
//Joins room
socket.join(OpenRoom[OpenRoom.length - 1].RID);
socket.RoomId = OpenRoom[OpenRoom.length - 1].RID;
//Creates room and fills information to it
socket.emit('JoinedRoom');
var NewRoom = new Room(OpenRoom[OpenRoom.length - 1].RID)
NewRoom.addPlayer(socket.id);
NewRoom.addSocket(socket);
Rooms.push(NewRoom);
OpenRoom[OpenRoom.length - 1].TimeOutID = setTimeout(CloseRoom, 5000, OpenRoom[OpenRoom.length - 1]);
}
//Checking if RoomId exists, it exists.
console.log(socket.RoomId);
//When I send 'test' to client, the client should print 'Succesfully Tested' to the console
//For io.to I dont get the message 'Succesfully Tested'
io.to(socket.RoomId).emit('Test');
//With socket.emit I get 'Succesfully Tested' message inside my console at the client side.
socket.emit('Test');
});
提前致谢
答案 0 :(得分:1)
默认情况下,在派生socket.id时,所有套接字都会连接到自己的个人房间,但要创建单独的房间,您需要在要成为房间一部分的套接字上调用data
。
之后,您将能够使用socket.join('foo');
向房间发送消息。另请注意,您还可以在io.to('foo').emit('test');
和broadcast
之间添加io.
您可以向所有套接字发送消息,但是发出呼叫的套接字。
.to
这也应该是
socket.join(OpenRoom[OpenRoom.length - 1].RID);
您需要使用socket.join(OpenRoom[OpenRoom[0]].RID);
在此范围内,您可以调用onTest函数并通过数据传递必要的信息。