Django Websockets Data going to the wrong Socket

和自甴很熟 提交于 2020-12-10 09:13:32

问题


Using Django Websockets + Channels, I create a (One) group and the message back and forth works just fine. Lets call this Group A

The problem starts when I open a SECOND group and a SECOND (Lets call this group B) WebSocket connection in a different browser.

The messages that I am trying to send to group A (first WebSocket connection), are going to group B (second WebSocket connection). All the messages that belong to group A go to the second WebSocket and the group B messages also go to the second socket.

Here's my consumer.py

import json
from asgiref.sync import async_to_sync
import logging

LOG = logging.getLogger(__name__)

from channels.generic.websocket import WebsocketConsumer, AsyncWebsocketConsumer


class EventConsumer(AsyncWebsocketConsumer):

    async def connect(self):
        self.id = self.scope['url_route']['kwargs']['id']
        self.group_name = f'enl_events_log_{self.id}'
        # Join room group
        await self.channel_layer.group_add(
            self.group_name,
            self.channel_name
        )

        await self.accept()

    async def disconnect(self, close_code):
        # Leave room group
        await self.channel_layer.group_discard(
            self.group_name,
            self.channel_name
        )

    # Receive message from WebSocket
    async def receive(self, text_data):
        # text_data_json = json.loads(text_data)
        # message = text_data_json['message']

        # Send message to room group
        await self.channel_layer.group_send(
            self.group_name,
            {
                'type': 'send.message',
                'message': "Message received"
            }
        )

    # Receive message from room group
    async def send_message(self, event):
        message = event['message']
        # Send message to WebSocket
        await self.send(text_data=json.dumps({
            'message': message
        }))

Here's my routing.py

from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter
from django.conf.urls import url

from app.consumers import EventConsumer

websocket_urlpatterns = [
    url(r'^enl_events/(?P<id>[^/]+)', EventConsumer()),
]

application = ProtocolTypeRouter({
    'websocket': AuthMiddlewareStack(
        URLRouter(
            websocket_urlpatterns
        )
    ),
})

Here's my ASGI.py + settings.py

import os
import django
from channels.routing import get_default_application

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'some_app.settings')

django.setup()

application = get_default_application()


--------------

ASGI_APPLICATION = "application"
WSGI_APPLICATION = 'application'


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

Here's my views.py

def events(request: HttpRequest) -> HttpResponse:
    channel_layer = get_channel_layer()
    async_to_sync(channel_layer.group_send)(
        'groupA_id',
        {'type': 'send.message', 'message': "please work"},
    )
    return HttpResponse(status=202)

I am running the frontend on port 3000

the backend I am running using

 Daphne some_app.asgi:application --port=9000

Notes: I am able to create the two WebSocket connections just fine. Why is there a data mismatch?

If I create a WebSocket for group A shouldn't the messages belonging to group A, go to group A/websocket 1?

LOGS provided below

[2020-11-17 17:17:03 +0000] [89629] [INFO] Configuring endpoint tcp:port=9000:interface=127.0.0.1
[2020-11-17 17:17:03 +0000] [89629] [INFO] Listening on TCP address 127.0.0.1:9000
127.0.0.1:62209 - - [17/Nov/2020:17:17:17] "WSCONNECTING /events/12345" - 
127.0.0.1:62209 - - [17/Nov/2020:17:17:17] "WSCONNECT /events/12345" - -
127.0.0.1:62265 - - [17/Nov/2020:17:17:26] "WSCONNECTING /events/56789" - 
127.0.0.1:62265 - - [17/Nov/2020:17:17:26] "WSCONNECT /events/56789" - -

回答1:


So, I figured out what was causing the issues.

The routing was missing as_asgi()

from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter
from django.conf.urls import url

from app.consumers import EventConsumer

websocket_urlpatterns = [
    url(r'^events/(?P<id>[^/]+)', EventConsumer().as_asgi()),
]

application = ProtocolTypeRouter({
    'websocket': AuthMiddlewareStack(
        URLRouter(
            websocket_urlpatterns
        )
    ),
})


来源:https://stackoverflow.com/questions/64870719/django-websockets-data-going-to-the-wrong-socket

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!