» Python: Make Web Chat App with Socket.IO » 2. Development » 2.3 Chat Messages

Chat Messages

To the server side, one-on-one chat is basically to forward messages from one socket to another.

Update main.py:

@@ -17,6 +17,11 @@ async def user_join(sid, user):
         return
     print(f"User {sid} => {user['emoji']} {user['name']} joined")
     users[sid] = {**user, 'sid': sid}
-    print(list(users.items()))
     # Broadcast to all connected clients
     await sio.emit('contacts', list(users.items()))
+
+
+@sio.event
+async def chat(sid, data):
+    to = data['to']
+    await sio.emit('chat', data, room=to)

data has below fields:

  • to: destination socket ID of the incoming message.
  • from: socket ID of the sender.
  • msg: message content.

sio.emit() with a room parameter allows you to target specific sockets or rooms when emitting events.

PrevNext