本文介绍了Django Websockets数据进入错误的套接字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Django Websockets + Channels,我创建了一个(One)组,来回传递消息的效果很好.让我们称之为A组

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

当我在另一个浏览器中打开SECOND组和SECOND(称为B组)WebSocket连接时,问题就开始了.

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

我要发送到组A(第一个WebSocket连接)的消息将发送到组B(第二个WebSocket连接).属于组A的所有消息都转到第二个WebSocket,而组B的消息也转到第二个套接字.

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.

这是我的 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
        }))

这是我的 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
        )
    ),
})

这是我的ASGI.py + settings.py

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)],
        },
    },
}

这是我的 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)

我正在端口3000上运行前端

I am running the frontend on port 3000

我正在使用的后端

 Daphne some_app.asgi:application --port=9000

注意:我能够创建两个WebSocket连接.为什么数据不匹配?

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

如果我为A组创建一个WebSocket,不应该将消息属于A组,请转到A组/websocket 1?

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

下面提供的日志

[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" - -

推荐答案

所以,我弄清楚了导致问题的原因.

So, I figured out what was causing the issues.

缺少路由 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
        )
    ),
})

这篇关于Django Websockets数据进入错误的套接字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-07 05:53