gpt4 book ai didi

python - Django Websockets 数据转到错误的套接字

转载 作者:行者123 更新时间:2023-12-05 06:57:32 28 4
gpt4 key购买 nike

使用 Django Websockets + Channels,我创建了一个(一个)组,来回消息工作得很好。让我们称之为 A 组

当我在不同的浏览器中打开第二个组和第二个(让我们称这个组为 B)WebSocket 连接时,问题就开始了。

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

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

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 上运行前端

我正在运行的后端

 Daphne some_app.asgi:application --port=9000

注意:我能够很好地创建两个 WebSocket 连接。为什么会出现数据不匹配?

如果我为 A 组创建 WebSocket,属于 A 组的消息不应该转到 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" - -

最佳答案

所以,我找出了导致问题的原因。

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

关于python - Django Websockets 数据转到错误的套接字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64870719/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com