WebSocket 握手 /ws/ [127.0.0.1:54395] WebSocket 断开连接 /ws/ [127.0.0.1:54395]
我的网络套接字在握手后断开连接。请建议可以遵循的解决方案或教程,以使用 django 中的频道实现基本聊天功能。
我的代码:
class Experience(AsyncWebsocketConsumer):
async def connect(self):
self.room_name = self.scope['url_route']['kwargs']['room_name']
self.room_group_name = 'chat_%s' % self.room_name
await self.channel_layer.group_add(
self.room_group_name,
self.channel_name
)
await self.accept()
async def disconnect(self, close_code):
await self.channel_layer.group_discard(
self.room_group_name,
self.channel_name
)
async def receive(self, text_data):
text_data_json = json.loads(text_data)
message = text_data_json['message']
username = text_data_json['username']
await self.channel_layer.group_send(
self.room_group_name,
{
'type': 'chatroom_message',
'message': message,
'username': username,
}
)
async def chatroom_message(self, event):
message = event['message']
username = event['username']
await self.send(text_data=json.dumps({
'message': message,
'username': username,
}))
pass
websocket_urlpatterns = [ path(r'ws/chat/(?P<room_name>\w+)/$', Experience.as_asgi()), ]
application = ProtocolTypeRouter({
'http': asgi_app,
'websocket': AuthMiddlewareStack(
URLRouter(
websocket_urlpatterns
)), # new
})
CHANNEL_LAYERS = {
"default": {
"BACKEND": "channels_redis.core.RedisChannelLayer",
"CONFIG": {
"hosts": [("localhost", 6379)],
},
},
}
我的网络套接字在握手后断开连接。请建议可以遵循的解决方案或教程,以使用 django 中的频道实现基本聊天功能。
我认为,通过连接到
/ws/
,您正在尝试连接到不存在的路线。由于未指定,服务器会断开您的连接。
您的 websocket_urlpatterns 正在指定可用的路由。尝试连接到
ws/chat/1
(或者 ws/chat/1/
,如果第一个不起作用)
要添加
/ws/
路线,请添加到您的 websocket_urlpatterns 下一行
path(r'ws/', Experience.as_asgi())