我在尝试向Flask-SocketIO中的特定客户端发送消息时遇到困难。为了简单起见,我已经取出了数据库逻辑和其他一些代码,因为我认为它们与我当前遇到的问题无关。
编辑2:我解决了这个问题。每当我连接并调用 handle_user_connection 函数时。我没有指定服务器将向其发送 user_connected 消息的客户端。在服务器端代码的第3行中可以看到这一点。
服务器端
@socketio.on('connect')
def handle_user_connect():
socketio.emit("user_connected", {"id":request.sid},callback=messageReceived,room=request.sid)
@socketio.on("join")
def on_join(data):
client = request.sid
room = f"{data['chatroom_name']}-{data['chatroom_id']}"
join = user_num < user_limit
if join:
join_room(room)
sessions[client] = room #sessions is an ordered dictionary of users and the rooms they join
print(room)
socketio.emit("join",room=client)
socketio.emit("room_status", {'room_status': user_num}, room=room)
else:
print(f"room {name} full.")
客户端
var socket = io.connect("http://127.0.0.1:5000" ,{'sync disconnect on unload': true });
socket.on("user_connected", function() {
socket.emit("join", {id: chatroom_id, name: chatroom_name})
});
socket.on("join",function (msg) {
prompt_username_change(msg)
});
socket.on("room_status",function (msg) {
update_user_number(msg);
});
每当我尝试仅向客户端发出加入消息时,如服务器端代码的第10行所示,服务器就会向房间内的所有用户发出加入消息。在用户加入名为“ roomtest-10”的会议室的示例中可以看到这一点。
emitting event "join" to c557f6c6804c47e5994ef340cabd81ed [/]
c557f6c6804c47e5994ef340cabd81ed: Sending packet MESSAGE data 2["join"]
emitting event "room_status" to roomtest-10 [/]
c557f6c6804c47e5994ef340cabd81ed: Sending packet MESSAGE data 2["room_status",{"room_status":1}]
127.0.0.1 - - [26/Apr/2020 14:58:23] "POST /socket.io/?EIO=3&transport=polling&t=N6saJeC&sid=7e72f51ad61b42f189ec96d85dfe2001 HTTP/1.1" 200 -
7e72f51ad61b42f189ec96d85dfe2001 is entering room roomtest-10 [/]
emitting event "join" to 7e72f51ad61b42f189ec96d85dfe2001 [/]
即使7e72f51ad61b42f189ec96d85dfe2001已经在会议室中,联接也会对它们感到不满,从而导致许多问题。
编辑:我添加了服务器日志的另一个示例,并在打印语句中添加了该语句,以显示当单个用户尝试加入而另一个用户已经连接时客户端的值。
67a17a8d161741cea1a72a0ad6c05fc4: Received packet MESSAGE data 2["join",{"id":"45","name":"roomtest"}]
received event "join" from 67a17a8d161741cea1a72a0ad6c05fc4 [/]
LOGGING USER SESSION ID: e1e0d3dd17414795b887d291c15e9218
127.0.0.1 - - [26/Apr/2020 15:34:34] "POST /socket.io/?EIO=3&transport=polling&t=N6sibpv&sid=67a17a8d161741cea1a72a0ad6c05fc4 HTTP/1.1" 200 -
67a17a8d161741cea1a72a0ad6c05fc4 is entering room roomtest-45 [/]
emitting event "join" to 67a17a8d161741cea1a72a0ad6c05fc4 [/]
67a17a8d161741cea1a72a0ad6c05fc4: Sending packet MESSAGE data 2["join"]
LOGGING USER SESSION ID: 67a17a8d161741cea1a72a0ad6c05fc4
127.0.0.1 - - [26/Apr/2020 15:34:34] "GET /socket.io/?EIO=3&transport=polling&t=N6sibpy&sid=67a17a8d161741cea1a72a0ad6c05fc4 HTTP/1.1" 200 -
emitting event "room_status" to roomtest-45 [/]
谢谢!