简体   繁体   中英

Django Channels - Unable To Message Channel Directly When A Member Of A Group

I have a requirement within my application to be able to message both individual channels and groups of channels depending on the situation.

I have come across the issue however, that if I add my channels to a group, I am no longer able to message them directly.

Here are some examples:

(Unable to send to a single channel):

class NonWorkingExampleConsumer(WebsocketConsumer):
    def connect(self):
        self.group_name = 'group'
        async_to_sync(self.channel_layer.group_add)(
            self.group_name,
            self.channel_name
        )
        
        self.accept()
    
    def disconnect(self, close_code):
        async_to_sync(self.channel_layer.group_discard)(
            self.group_name,
            self.channel_name
        )
        
    def receive(self, text_data):
        async_to_sync(self.channel_layer.send)(
            self.channel_name,
            {
                'type' : 'test',
                'message' : 'Hello World!'
            }
        )
        
    def test(self, event):
        self.send(text_data=json.dumps({
            'message' : event['message']
        }))

(Able to send to a single channel):

class WorkingExampleConsumer(WebsocketConsumer):
    def connect(self):       
        self.accept()
    
    def disconnect(self, close_code):
        pass
        
    def receive(self, text_data):
        async_to_sync(self.channel_layer.send)(
            self.channel_name,
            {
                'type' : 'test',
                'message' : 'Hello World!'
            }
        )
        
    def test(self, event):
        self.send(text_data=json.dumps({
            'message' : event['message']
        }))

So, My question is: Is this a bug or am I simply doing something wrong? I was considering opening a ticket on Django Channels GitHub, but it suggested checking on StackOverflow first to make sure it was definitely a bug and not user error (which is a real possibility!)

I am using Django version 3.1,Django Channels version 3.0.2 and Django Channels Redis Version 3.2.0. Here are my Redis settings:

CHANNEL_LAYERS = {
    'default': {
        'BACKEND': 'channels_redis.core.RedisChannelLayer',
        'CONFIG': {
            "hosts": [('192.168.15.82', 6379)],
        },
    },
}

Any help is greatly appreciated.

I'm not entirely sure as to why, but after a nights sleep and some tinkering with my code this now appears to be working as intended.

That does indeed answer the question, it was user error all along!

Sorry for wasting your time, but thanks very much for attempting to solve the issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM