简体   繁体   English

无法使用 Flask-SocketIO 向房间发送消息

[英]Cannot emit message to room using Flask-SocketIO

I am building a simple chat app and I have been trying to emit messages to rooms with Flask-SocketIO.我正在构建一个简单的聊天应用程序,我一直在尝试使用 Flask-SocketIO 向房间发送消息。

The "mesage_event" event from the client reaches the server well, but then, I cannot see anything on the client side.来自客户端的“mesage_event”事件很好地到达服务器,但是,我在客户端看不到任何东西。 I don't know whether the server emits something to the room but on the client side, I cannot see anything in the console.我不知道服务器是否向房间发送了一些东西,但在客户端,我在控制台中看不到任何东西。 I can only successfully send to all clients with broadcasting.我只能通过广播成功发送给所有客户端。

Here is my code on the server side:这是我在服务器端的代码:

@socketio.on("send msg")
def sendsocket(data):
    print("send msg start:", data["msg"])
    msg = data["msg"]
    room = data["room"]
    emit("message_event", msg, room = room)

And the client side:和客户端:

1- for sending the message: 1-用于发送消息:

socket.emit('send msg', {'msg': msg, 'room': room})

2- for triggering the event handler: 2-用于触发事件处理程序:

socket.on('message_event', data => {
    console.log("message received:", data);
});

You are missing 2 things.你错过了两件事。

1st , you need to send a "join" event to the server.第一,您需要向服务器发送"join"事件。

<script>
function joinRoom() {
    console.log("ask server to join room");
    socket.emit("join", { "user": Date.now(), "room": "Notifications" });
}
</script>

<body>
    <button onclick="joinRoom()">Join</button>
</body>

For example, here I attached the trigger to a button.例如,在这里我将触发器附加到按钮上。 And to make it easier to initially test adding users to rooms, I use Date.now() as the username.为了更容易地测试将用户添加到房间,我使用Date.now()作为用户名。 You can open different tabs to serve as different users.您可以打开不同的选项卡以充当不同的用户。

2nd , you need to have a handler for that join event.第二,您需要有一个用于该join事件的处理程序。
There is an example in the Rooms and Namespaces section of the Flask-SocketIO docs. Flask-SocketIO 文档的房间和命名空间部分有一个示例。

@socketio.on("join")
def on_join(data):
    user = data["user"]
    room = data["room"]
    print(f"client {user} wants to join: {room}")
    join_room(room)
    emit("room_message", f"Welcome to {room}, {user}", room=room)

In the handler, you need to call the join_room method to add the user to a room under the current namespace .在处理程序中,您需要调用join_room方法将用户添加到当前命名空间下的房间。 Note that part about the namespace.请注意有关命名空间的部分。 By default all connections are under the root ( / ) namespace.默认情况下,所有连接都在根 ( / ) 命名空间下。 If you have custom namespaces, then each namespace will have their own rooms.如果您有自定义命名空间,那么每个命名空间都会有自己的房间。

There is also a corresponding leave_room method.还有一个对应的leave_room方法。

Here is the complete server-side code:这是完整的服务器端代码:

@socketio.on("connect")
def connect():
    print("client wants to connect")
    emit("status", { "data": "Connected. Hello!" })

@socketio.on("join")
def on_join(data):
    user = data["user"]
    room = data["room"]
    print(f"client {user} wants to join: {room}")
    join_room(room)
    emit("room_message", f"Welcome to {room}, {user}", room=room)

Here is the complete client-side code:这是完整的客户端代码:

<script type="text/javascript" charset="utf-8">
    const socket = io();
    socket.on("connect", () => {
        console.log("connect");
    });
    socket.on("status", (status) => {
        console.log("received status: " + status.data);
    });
    socket.on("room_message", (msg) => {
        console.log("message from room: " + msg);
    });
    function joinRoom() {
        console.log("ask server to join room");
        socket.emit("join", { "user": Date.now(), "room": "Notifications" });
    }
</script>

<body>
    <button onclick="joinRoom()">Join</button>
</body>

Now, you can now open multiple tabs and connect each one to the server.现在,您现在可以打开多个选项卡并将每个选项卡连接到服务器。 The server-side should show the following messages:服务器端应显示以下消息:

client wants to connect
client wants to connect
client wants to connect
client 1582428076724 wants to join: Notifications
client 1582428080023 wants to join: Notifications
client 1582428082916 wants to join: Notifications

And on the 1st user to join the room (1582428076724), you should be able to see the logs as other users are joining the room.在第一个用户加入房间 (1582428076724) 时,您应该能够看到其他用户加入房间时的日志。

connect 
received status: Connected. Hello!
ask server to join room 
message from room: Welcome to Notifications, 1582428076724 
message from room: Welcome to Notifications, 1582428080023 
message from room: Welcome to Notifications, 1582428082916

Don't know why send and emit function from flask_socketio does not work.不知道为什么flask_socketio 的发送和发射功能不起作用。 If I use socketio (socket instance), it will send the message successfully.如果我使用 socketio(套接字实例),它将成功发送消息。

socketio.emit('EVENT_NAME', data, to='YOUR_ROOM')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM