WebSocket DISCONNECT
来源:9-14 前端WebSocket API讲解
Otiose
2021-04-07
老师我的私信模块的websocket一直都是报错无法握手(包括notifications模块也是无法握手成功):
WebSocket HANDSHAKING /ws/test1/ [192.168.60.1:63543]
WebSocket DISCONNECT /ws/test1/ [192.168.60.1:63543]
如果忽略这个错误,直接发信息给其他用户的话就会报如下错误:
Not Found: /messages/send-message/
HTTP POST /messages/send-message/ 404 [0.01, 192.168.60.1:63873]
检查了很多次实在无法解决,我的版本django2.2,channels2.4。
class MessagesConsumer(AsyncWebsocketConsumer):
"""处理私信应用中的Websocket请求"""
async def connect(self):
"""加入聊天组"""
if self.scope['user'].is_anonymous:
await self.close()
else:
await self.channel_layer.group.add(self.scope['user'].username, self.channel_name)
await self.accept()
async def receive(self, text_data=None, bytes_data=None):
"""接收私信"""
await self.send(text_data=json.dumps(text_data))
async def disconnect(self, code):
"""离开聊天组"""
await self.channel_layer.group.discard(self.scope['user'].username, self.channel_name)
application = ProtocolTypeRouter({
'websocket': AllowedHostsOriginValidator(
AuthMiddlewareStack(
URLRouter([
path('ws/notifications/', NotificationsConsumer),
path('ws/<str:username>/', MessagesConsumer),
])
)
)
})
@login_required
@ajax_required
@require_http_methods(["POST"])
def send_message(request):
"""发送私信"""
sender = request.user
recipient_username = request.POST["to"]
recipient = get_user_model().objects.get(username=recipient_username)
message = request.POST["message"]
if len(message.strip()) != 0 and sender != recipient:
msg = Message.objects.create(
sender=sender,
recipient=recipient,
message=message
)
channel_layer = get_channel_layer()
payload = {
'type': 'receive',
'message': render_to_string('messager/single_message.html', {'message': msg}),
'sender': sender.username
}
async_to_sync(channel_layer.group.send)(recipient_username, payload)
return render(request, 'messager/single_message.html', {"message": msg})
return HttpResponse()
app_name = 'messager'
urlpatterns = [
path('', views.MessagesListView.as_view(), name="messages_list"),
path('send-message/', views.send_message, name="send_message"),
path('<username>/', views.ConversationListView.as_view(), name="conversation_detail"),
]
messager.js 与您的源代码一致
麻烦老师帮我看看~
写回答
2回答
-
group.add ----> group_add
同理,其他错的也改了
122021-04-08 -
慕的地2047357
2021-05-11
老大哥 问题解决了嘛?我报同样的错误,困住很久了。请求回复
012021-05-11
相似问题