我在Node.js中构建服务器套接字,这是我无法向特定房间发送数据的问题。我试图在房间里打印所有socket-client id,它仍然会在那个房间打印所有套接字ID。
function SocketManager(serverSocket, app) {
let self = this;
self.io = socket.listen(serverSocket);
self.io.on('connection', function (client) {
let user_id;
client.on('join', function (userId) {
user_id = userId;
logger.info("SOCKET: User " + userId + " connected with id " + client.id);
client.join(userId);
});
client.on('disconnect', function () {
if (user_id)
logger.info("SOCKET: User " + user_id + " disconnected with id " + client.id);
});
client.on('push_data', function (sensor_data) {
let sensor_id = sensor_data.sensorId;
app.models.sensor.findById(sensor_id).then(function (sensor) {
let userId = sensor.createdBy;
if (self.io.nsps["/"].adapter.rooms[userId]) {
Object.keys(self.io.nsps["/"].adapter.rooms[userId].sockets).forEach(function (socket) {
logger.info(socket);
});
self.io.in(userId).emit('pull_data', sensor_data);
}
// self.io.emit('pull_data', sensor_data);
});
});
});
}
当我替换self.io.in(userId).emit('pull_data', sensor_data)
时
使用self.io.emit('pull_data', sensor_data)
,客户端可以正常接收数据。客户端使用Swift SocketIO。