我无法将活动广播到特定的房间。
我检查房间里的客户,他们似乎已正确加入房间。
然而socket.broadcast.to(socket.roomChannel).emit("cardSelected", cardInfo)
根本就没有用,
而socket.broadcast.emit("cardSelected", cardInfo)
有效(但我只需要向房间广播)。
这让我疯了...... 这是我的代码,不起作用的部分一直到底:
// Setup basic express server
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
var port = '4000';
server.listen(port, function () {
});
this.rooms = [];
let lastRoomId = 0
let lastPlayerId = 0
io.on('connection', function (socket) {
// send list of rooms at connect
socket.emit("connected", {rooms: this.rooms});
socket.id = ++lastPlayerId;
// Room
socket.on('createRoom', (roomName) => {
const room = {
id: ++lastRoomId,
name: roomName,
players: [],
}
this.rooms.push(room);
socket.emit("roomCreated", room);
socket.broadcast.emit("update_rooms", {rooms: this.rooms});
});
socket.on('joinRoom', (id) => {
const index = this.rooms.map(room => room.id).indexOf(id);
if (index >= 0) {
this.rooms[index].players.push(socket.id);
socket.emit("roomJoined", this.rooms[index]);
socket.roomId = id;
socket.roomChannel = this.rooms[index].name;
socket.join(socket.roomChannel);
socket.broadcast.emit("update_rooms", {rooms: this.rooms});
}
});
// Game
socket.on('cardSelected', (cardInfo) => {
console.log("broadcasting to", socket.roomChannel);
console.log("socket room", socket.rooms);
var clients = io.sockets.adapter.rooms[socket.roomChannel].sockets;
// Shows that the clients ARE in the room
// returns "{ '1': true, '2': true }" if I have two clients
console.log(clients);
// DOESNT WORK!!
socket.broadcast.to(socket.roomChannel).emit("cardSelected", cardInfo)
// DOESNT WORK!!
io.to(socket.roomChannel).emit("cardSelected");
// Works
socket.broadcast.emit("cardSelected", cardInfo);
});
});
我也试过socket.to(socket.roomChannel).emit("cardSelected", cardInfo);
(没有广播),没有任何成功
答案 0 :(得分:0)
调试socket.io中的代码后,我发现更改套接字的“id”值会破坏所有内容!
我删除了这一行socket.id = ++lastPlayerId;
,现在一切正常:)
所以,请记住:永远不要手动更改套接字的ID 。