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

Group Messages

Create Group

A Socket.IO room is a virtual concept that allows you to group sockets (connections) together. Sockets that are in the same room can communicate with each other easily. This feature is very useful when you want to broadcast messages to specific groups of clients, rather than broadcasting to all connected clients.

Changes in main.py:

@@ -25,3 +25,13 @@ async def user_join(sid, user):
 async def chat(sid, data):
     to = data['to']
     await sio.emit('chat', data, room=to)
+
+
+@sio.on('create-group')
+# Create Room
+async def create_group(sid, data):
+    socketIds, roomName, roomId = data['sids'], data['name'], data['id']
+    for socketId in socketIds:
+        await sio.enter_room(socketId, roomId)
+    await sio.emit('create-group', data, room=roomId)
+    print(f"Room {roomId} => {roomName} created")
  • sids has all the socket IDs of users in a to-be-created group.
  • roomId is a unique alphanumeric string, which is more suitable than a user inputed room name here.

sio.emit("create-group", ..., room=roomId) notifies all the participants that a new group has been created.

Forward Group Messages

Changes in main.py:

@@ -27,6 +27,12 @@ async def chat(sid, data):
     await sio.emit('chat', data, room=to)
 
 
+@sio.on('group-chat')
+async def group_chat(sid, data):
+    roomId = data['room']
+    await sio.emit('group-chat', data, room=roomId, skip_sid=sid)
+
+
 @sio.on('create-group')
 # Create Room
 async def create_group(sid, data):

sio.emit(..., room=roomId, skip_sid=sid) forwards the messages to all the participants in the room except the sender.

PrevNext