How to limit number of clients in django channels' room

Viewed 347

I wish to limit the number of users in a room to 2 because I am making a socket game were two palyers can play a tic-tack-toe or a connect-4 game so I a trying to find some way of limiting only 2 players in one room.

Down below is my comsumers.py

from channels.generic.websocket import WebsocketConsumer
from asgiref.sync import async_to_sync
import json


class GameRoom(WebsocketConsumer):

    def connect(self):
        self.room_name = self.scope['url_route']['kwargs']['room_code']
        self.room_group_name = 'room_%s' % self.room_name
        print(self.room_group_name)
        async_to_sync(self.channel_layer.group_add)(
            self.room_group_name,
            self.channel_name
        )

        self.accept()

I have removed some of the less necessary methods from this question

1 Answers

You have to create a room model in your project and save the connected users to it, then you can add a validation in your connect method, something like this:

def connect(self):
    self.room_name = self.scope['url_route']['kwargs']['room_code']
    
    self.room = Room.objects.get(code=self.room_name)
    if self.room.connected_user >= 2:
        return self.close()
    else:
        self.room.connected_user = self.room.connected_user + 1
        self.room.save(update_fields=['connected_user'])

        self.room_group_name = 'room_%s' % self.room_name
        print(self.room_group_name)
        async_to_sync(self.channel_layer.group_add)(
            self.room_group_name,
            self.channel_name
        )

        self.accept()


def disconnect(self):
    ...
    self.room.connected_user = self.room.connected_user - 1 
    self.room.save(update_fields=['connected_user'])
  • Extra:

    and of course, you can use the F() function, and make your performance better in connect and disconnect (useful when many users trying to connect in the same time)

Related