简体   繁体   English

如何使用socket.io连接Flask中的多个客户端?

[英]How to connect multiple clients in Flask using socket.io?

I want to get data in my Flask server from a socket.io client. 我想从socket.io客户端获取Flask服务器中的数据。 My setting is: 我的设置是:

  1. Client1 calls method request_data on server. Client1在服务器上调用方法request_data。
  2. The method request_data then emits 'client2' event on Client2. 然后,方法request_data在Client2上发出“ client2”事件。

I have the following method in my flask server: 我的Flask服务器中有以下方法:

@socketio.on('client1')
def test_message(message):                    
    emit('client2', {'data': 'testdata'})

On the client that should receive the data: 在应接收数据的客户端上:

$(document).ready(function(){
    var socket = io.connect('http://' + document.domain + ':'+location.port);
    socket.on('connect', function() {
        socket.emit('my event', {data: 'I\'m connected!'});
    });

    socket.on('client2', function(msg) {
        console.log(msg.data)
        console.log("here")
    });
  });

But I cannot seem to establish the connection to client2. 但是我似乎无法建立与client2的连接。 What am I doing wrong here? 我在这里做错了什么?

When you call the emit function without explicitly indicating a recipient, then the event is sent back to the caller, which in your example is the client that sent the client1 event to the server. 当您在没有显式指示接收者的情况下调用emit函数时,该事件将被发送回调用方,在您的示例中,该调用方是将client1事件发送到服务器的客户端。

If you want to emit to a different client, you need to know its session id (or sid ). 如果要发送给其他客户端,则需要知道其会话ID(或sid )。 In any handler, you can use request.sid to obtain the session ID of the sender. 在任何处理程序中,都可以使用request.sid获取发送者的会话ID。 So for example, you could write a connect handler that records these session IDs attached to your application specific data, and then when you want to send something to a specific client, do something like this: 因此,例如,您可以编写一个连接处理程序,记录连接到您的应用程序特定数据的这些会话ID,然后在您想要向特定的客户端发送消息时执行以下操作:

emit('client2', {'data': 'testdata'}, room=get_sid_for_user(username))

Here the room argument specifies which room to emit the message to. 在这里, room参数指定将消息发送到哪个房间。 All users have a default room that is named with their session ID. 所有用户都有一个默认会议室,该会议室以其会话ID命名。

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

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