【发布时间】:2018-12-11 13:53:35
【问题描述】:
我想使用 socket.io 实现多个聊天,我可以使用一个 socket.room 实现一对一聊天,但我想创建多个 socket 房间以与多人并行聊天
以下是我在 git 中获得的示例,但我无法理解它如何用于多个聊天,任何人都可以解释一下
服务器端
io = socketio.listen(server);
// handle incoming connections from clients
io.sockets.on('connection', function(socket) {
// once a client has connected, we expect to get a ping from them
saying what room they want to join
socket.on('room', function(room) {
socket.join(room);
});
});
// now, it's easy to send a message to just the clients in a given
room
room = "abc123";
io.sockets.in(room).emit('message', 'what is going on, party
people?');
// this message will NOT go to the client defined above
io.sockets.in('foobar').emit('message', 'anyone in this room yet?');
客户端
// set-up a connection between the client and the server
var socket = io.connect();
// let's assume that the client page, once rendered, knows what room
it wants to join
var room = "abc123";
socket.on('connect', function() {
// Connected, let's sign-up for to receive messages for this room
socket.emit('room', room);
});
socket.on('message', function(data) {
console.log('Incoming message:', data);
});
【问题讨论】:
标签: javascript node.js socket.io