【问题标题】:Django Channels: Data Going to the Wrong SocketDjango 通道:数据进入错误的套接字
【发布时间】:2021-03-14 17:45:57
【问题描述】:

尽管在我的路由中调用了 as_asgi 方法,但我面临着同样的 issue。数据总是发送到第二个套接字。 Channels V3.0 和 Django V3.1.2 正在使用中。

routing.py

websocket_urlpatterns = [
    re_path(WS_PREFIX + r'room/(?P<room_name>\w+)/$', RoomConsumer().as_asgi()),
]

asgi.py

import routing
django_asgi_app = get_asgi_application()


application = ProtocolTypeRouter({
    "http": get_asgi_application(),
    # Just HTTP for now. (We can add other protocols later.)

    "websocket": AuthMiddlewareStack(
        URLRouter(
            routing.websocket_urlpatterns
        )
    ),
})

本地服务器日志:

WebSocket HANDSHAKING /ws/room/2/ [127.0.0.1:63280]
WebSocket CONNECT /ws/room/2/ [127.0.0.1:63280]
WebSocket HANDSHAKING /ws/room/1/ [127.0.0.1:63288]
WebSocket CONNECT /ws/room/1/ [127.0.0.1:63288]

consumer.py:

import json
from channels.generic.websocket import AsyncWebsocketConsumer

class RoomConsumer(AsyncWebsocketConsumer):
    async def connect(self):
        self.room_name = self.scope['url_route']['kwargs']['room_name']
        self.room_group_name = 'room_%s' % self.room_name

        # Join room group
        await self.channel_layer.group_add(
            self.room_group_name,
            self.channel_name
        )

        await self.accept()

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

    # Receive message from WebSocket
    async def receive(self, text_data):
        text_data_json = json.loads(text_data)
        
        # Send message to room group
        await self.channel_layer.group_send(
            self.room_group_name,
            {
                'type': 'send_data',
                'message': "Message received"
            }
        )

    # Receive message from room group
    async def send_data(self, event):
        # Send message to WebSocket
        await self.send(text_data=json.dumps(event))

这就是我发送数据的方式:

result['type'] = 'send_data'
result['test'] = 'test'
layer = get_channel_layer()
async_to_sync(layer.group_send)('room_2', result)
return HttpResponse(status=202)

还有什么我需要考虑的吗?

【问题讨论】:

    标签: django sockets channels


    【解决方案1】:

    我刚刚意识到有更新版本的频道可用。我更新到了 V3.0.2 频道,现在可以正常工作了。

    【讨论】:

      猜你喜欢
      • 2021-02-28
      • 2018-11-10
      • 2010-10-26
      • 1970-01-01
      • 2011-10-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-25
      相关资源
      最近更新 更多