gpt4 book ai didi

sockets - socket.io动态发送和接收消息

转载 作者:行者123 更新时间:2023-12-03 12:05:12 25 4
gpt4 key购买 nike

如何将消息发送到动态 session 室,以及当服务器收到该消息时,如何将该消息发送到其他成员所在的同一个 session 室?
table_id是房间,它将动态设置。

客户:

var table_id = 1; // example, python will give this value

var socket = io('http://localhost:3000');
socket.on('connect', function() {
console.log('Connected');
socket.emit('join', "table_"+table_id);
});

socket.on("table_"+table_id, function(data) {
console.log('New data:', data);
});

$('button').on('click', function(){
// send message to that room
});

服务器:
io.on('connection', function(socket){

socket.on('join', function(table) {
console.log('joined to table '+table);
socket.join(table);
});

// when receive message from particular room, send it back to others in same room

});

最佳答案

也许您需要 namespace ,而不是房间。
您可以在一个 namespace 中为该 session 室中的所有成员广播事件。

http://socket.io/docs/rooms-and-namespaces/

但是,如果您想进行经典的聊天消息,只需将消息广播到整个房间即可:

io.to('some room').emit('some event');

例如:
io.on('connection', function(socket){
socket.on('join', function(table) {
console.log('joined to table '+table);
socket._room = table
socket.join(table);
});
// when receive message from particular room, send it back to others in same room
socket.on('message', function(message) {
io.to(socket._room).emit('some event',message);
});
});

和客户端:
$('button').on('click', function(){
// send message to that room
socket.emit('message', $('.message').val());
});

关于sockets - socket.io动态发送和接收消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25676990/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com