简体   繁体   中英

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

I want to get data in my Flask server from a socket.io client. My setting is:

  1. Client1 calls method request_data on server.
  2. The method request_data then emits 'client2' event on Client2.

I have the following method in my flask server:

@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. 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.

If you want to emit to a different client, you need to know its session id (or sid ). In any handler, you can use request.sid to obtain the session ID of the sender. 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:

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

Here the room argument specifies which room to emit the message to. All users have a default room that is named with their session ID.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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