Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

flask socketio emit to specific user

Tags:

I see there is a question about this topic, but the specific code is not outlined. Say I want to emit only to the first client.

For example (in events.py):

clients = []  @socketio.on('joined', namespace='/chat') def joined(message):     """Sent by clients when they enter a room.     A status message is broadcast to all people in the room."""     #Add client to client list     clients.append([session.get('name'), request.namespace])     room = session.get('room')     join_room(room)     emit('status', {'msg': session.get('name') + ' has entered the room.'}, room=room)     #I want to do something like this, emit message to the first client     clients[0].emit('status', {'msg': session.get('name') + ' has entered the room.'}, room=room) 

How is this done properly?

Thanks

like image 704
shell Avatar asked Sep 10 '16 07:09

shell


People also ask

What is SocketIO in Flask?

Flask-SocketIO gives Flask applications access to low latency bi-directional communications between the clients and the server.

What is SocketIO Python?

Socket.IO is a library that enables real-time, bidirectional and event-based communication between the browser and the server. It consists of: a Node. js server: Source | API. a Javascript client library for the browser (which can be also run from Node.


1 Answers

I'm not sure I understand the logic behind emitting to the first client, but anyway, this is how to do it:

clients = []  @socketio.on('joined', namespace='/chat') def joined(message):     """Sent by clients when they enter a room.     A status message is broadcast to all people in the room."""     # Add client to client list     clients.append(request.sid)      room = session.get('room')     join_room(room)      # emit to the first client that joined the room     emit('status', {'msg': session.get('name') + ' has entered the room.'}, room=clients[0]) 

As you can see, each client has a room for itself. The name of that room is the Socket.IO session id, which you can get as request.sid when you are handling an event from that client. So all you need to do is store this sid value for all your clients, and then use the desired one as room name in the emit call.

like image 53
Miguel Avatar answered Sep 24 '22 06:09

Miguel