无法发送消息到特定的房间
我想发送消息到特定的房间(所有客户在房间里),我搜查了很多,并尝试这些选项:
io.in(socket.RoomId).emit('Test'); io.to(socket.RoomId).emit('Test'); io.sockets.in(socket.RoomId).emit('Test');
我想作为服务器发送,所以不用在房间里使用现有的sockets。 但是因为我找不到方法,我尝试了以下方法:
this.ListOfSockets[0].to(RoomId).emit('Test');
这不工作,所以我试图只是发射到这个sockets本身:
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'); });
提前致谢
默认情况下,当socket.id被派生出来时,所有的套接字都被连接到自己的私人空间,但是要创build分隔的房间,则需要调用socket.join('foo');
在你想成为一个房间的一部分sockets。
然后,你可以使用io.to('foo').emit('test');
发送消息到房间io.to('foo').emit('test');
另外请注意,你也可以在io.
之间添加broadcast
io.
和.to
将允许您发送一个消息, 除了谁打电话的sockets的所有sockets。
socket.join(OpenRoom[OpenRoom.length - 1].RID);
也应该是socket.join(OpenRoom[OpenRoom[0]].RID);
你需要使用socket.On('Test', data =>{ //code here})
在这个函数中,你可以调用函数onTest,并通过数据传递必要的信息。