在 socket.io
文档中,我看到了房间的示例
io.on('connection', function(socket){
socket.on('say to someone', function(id, msg){
socket.broadcast.to(id).emit('my message', msg);
});
});
我有一条路线 /rooms/:roomId
。
是否可以使服务器和客户端之间发送的套接字仅到达特定房间?
我想服务器应该是这样的
io.on('connection', function(socket){
socket.on('new msg from client', function(roomId, msg){
io.to(id).emit('new msg from server', msg);
});
});
上面,客户端应该发送消息
socket.emit('new msg from client', roomId, msg);
只需使用
即可获取新消息socket.on('new msg from server', function () {
document.getElementById('msgs').appendChild(...);
});
但这行得通吗?在执行此操作之前,我是否应该使用 socket.join(...)
加入房间?
最佳答案
对于我制作的俳句共享应用程序,我有这样的东西:
io.on('connection', function(socket) {
var socket_id = socket.id;
var client_ip = socket.handshake.headers['x-forwarded-for'] || socket.handshake.address.address;
clients.push(socket);
console.info('New client connected (id=' + socket.id + ').');
number_of_clients_connected++;
console.log('[' + client_ip + '] connected, ' + number_of_clients_connected + ' total users online.');
//when a socket is disconnected or closed, .on('disconnect') is fired
socket.on('disconnect', function() {
number_of_clients_connected--;
console.log('[' + client_ip + '] disconnected, ' + number_of_clients_connected + ' total users online.');
//on disconnect, remove from clients array
var index = clients.indexOf(socket);
if (index != -1) {
clients.splice(index, 1);
//console.info('Client gone (id=' + socket.id + ').');
}
});
因此它保留了一个客户端数组,当某些消息需要中继时,您可以指定客户端套接字 ID...
//reads from latest_haikus_cache and sends them
socket.on('request_haiku_cache', function() {
latest_haikus_cache.forEach(function(a_latest_haiku) {
clients[clients.indexOf(socket)].emit('load_haiku_from_cache', a_latest_haiku);
});
});
关于javascript - 使用带有 socket.io 的房间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39377254/