Piotr Kontowicz
Piotr Kontowicz

Reputation: 41

Django-channels sending message to group

I'm writing an app where I need to use sockets. To handle it I use django channels, but i can't broadcast message to group.

class waiting(WebsocketConsumer): 
    def connect(self): 
        self.channel_layer.group_add( 'my_group_name', self.channel_name )

        if <condition>:
            self.channel_layer.group_send( # This does not give any effect. I'm sure the condition is satisfied.
                'my_group_name',
                {
                    'message' : 'succes'
                }
            )

        self.accept()
        self.send(json.dumps({'message' : 'message'})) # This works perfect

    def disconnect(self, close_code):
        self.channel_layer.group_discard(
            'my_group_name',
            self.channel_name
        )

What I have wrong? I already read many tutorials and also documentation but I didn't find any solution. What I should change to make this code work as I want?

I'm using channels == 2.3.1 and Django 2.2.6.

Upvotes: 0

Views: 424

Answers (1)

Raja Simon
Raja Simon

Reputation: 10305

You're not actually accepting the connection in connect function before broadcasting. Without self.accept() connection will be rejected and closed.

Upvotes: 2

Related Questions