Django Channel Error: No handler for message type websocket.receive
Django Channel Error: No handler for message type websocket.receive
thread.html
<script>
//console.log(window.location)
var loc = window.location
var formData = $("#form")
var msgInput = $("#message_id")
var wsStart = 'ws://'
if (loc.protocol == 'https:') {
wsStart = 'wss://'
}
var endpoint = wsStart + loc.host + loc.pathname // EndPoint of the connection
var socket = new WebSocket(endpoint)
socket.onmessage = function(e){
console.log("message: ", e)}
socket.onopen = function(e){
console.log("open: ", e)
socket.send("Cool guys") //TRYING TO SEND THIS VIA THE SOCKET
}
socket.onerror = function(e){
console.log("error: ", e)}
socket.onclose = function(e){
console.log("close: ", e)}
</script>
consumers.py
import asyncio
import json
from django.contrib.auth import get_user_model
from channels.consumer import AsyncConsumer
from channels.db import database_sync_to_async
from .models import Thread, ChatMessage
class ChatConsumer(AsyncConsumer):
async def websocket_connect(self, event):
print("Connected", event)
await self.send({
"type": "websocket.accept"
})
# other_user = self.scope['url_route']['kwargs']['username']
# me = self.scope['user']
# thread_obj = await self.get_thread(me, other_user)
# print(other_user, me)
# print(thread_obj)
async def websocket_recieve(self, event):
print('Recieve', event)
await self.send({
"type": "websocket.send",
"text": event,
})
front_text = event.get('text', None)
if front_text is not None:
msg_json_dict = json.loads(front_text)
msg = msg_json_dict.get('message')
print(msg)
await self.send({
"type": "websocket.send",
"text": msg,
})
async def websocket_disconnect(self, event):
print("Disconnected", event)
# @database_sync_to_async
# def get_thread(self, user, other_user):
# return Thread.objects.get_or_new(user, other_user)[0]
给出错误
File "/home/pentester/.local/lib/python3.7/site-packages/channels/consumer.py", line 75, in dispatch
raise ValueError("No handler for message type %s" % message["type"])
No handler for message type websocket.receive
WebSocket DISCONNECT /messages/boy/ [127.0.0.1:37172]
No handler for the message type websocket.recieve is my headache now.
意向
我的意图是通过 thread.html 的套接字在方法 socket.onopen[ 下发送消息=30=] 但我总是收到一条错误消息,说 raise ValueError("No handler for message type %s" % message["type"]
套接字 url 模式
from channels.routing import ProtocolTypeRouter, URLRouter
from django.conf.urls import url, re_path
from channels.auth import AuthMiddlewareStack
from channels.security.websocket import AllowedHostsOriginValidator, OriginValidator
from chat.consumers import ChatConsumer
application = ProtocolTypeRouter({
'websocket':AllowedHostsOriginValidator(
AuthMiddlewareStack(
URLRouter(
[
url(r"^messages/(?P<username>[\w.@+-]+)/$", ChatConsumer),
]
)
)
)
})
我在这里回答是为了让事情更进一步。非常感谢您花时间添加 WebSocket URL 模式,我相信问题只是拼写错误。
把websocket_recieve
改成websocket_receive
就可以收到了
这些通道使用函数 _
转换为真正的套接字层的原因 websocket.receive
所以拼写很重要。
thread.html
<script>
//console.log(window.location)
var loc = window.location
var formData = $("#form")
var msgInput = $("#message_id")
var wsStart = 'ws://'
if (loc.protocol == 'https:') {
wsStart = 'wss://'
}
var endpoint = wsStart + loc.host + loc.pathname // EndPoint of the connection
var socket = new WebSocket(endpoint)
socket.onmessage = function(e){
console.log("message: ", e)}
socket.onopen = function(e){
console.log("open: ", e)
socket.send("Cool guys") //TRYING TO SEND THIS VIA THE SOCKET
}
socket.onerror = function(e){
console.log("error: ", e)}
socket.onclose = function(e){
console.log("close: ", e)}
</script>
consumers.py
import asyncio
import json
from django.contrib.auth import get_user_model
from channels.consumer import AsyncConsumer
from channels.db import database_sync_to_async
from .models import Thread, ChatMessage
class ChatConsumer(AsyncConsumer):
async def websocket_connect(self, event):
print("Connected", event)
await self.send({
"type": "websocket.accept"
})
# other_user = self.scope['url_route']['kwargs']['username']
# me = self.scope['user']
# thread_obj = await self.get_thread(me, other_user)
# print(other_user, me)
# print(thread_obj)
async def websocket_recieve(self, event):
print('Recieve', event)
await self.send({
"type": "websocket.send",
"text": event,
})
front_text = event.get('text', None)
if front_text is not None:
msg_json_dict = json.loads(front_text)
msg = msg_json_dict.get('message')
print(msg)
await self.send({
"type": "websocket.send",
"text": msg,
})
async def websocket_disconnect(self, event):
print("Disconnected", event)
# @database_sync_to_async
# def get_thread(self, user, other_user):
# return Thread.objects.get_or_new(user, other_user)[0]
给出错误
File "/home/pentester/.local/lib/python3.7/site-packages/channels/consumer.py", line 75, in dispatch
raise ValueError("No handler for message type %s" % message["type"])
No handler for message type websocket.receive
WebSocket DISCONNECT /messages/boy/ [127.0.0.1:37172]
No handler for the message type websocket.recieve is my headache now.
意向
我的意图是通过 thread.html 的套接字在方法 socket.onopen[ 下发送消息=30=] 但我总是收到一条错误消息,说 raise ValueError("No handler for message type %s" % message["type"]
套接字 url 模式
from channels.routing import ProtocolTypeRouter, URLRouter
from django.conf.urls import url, re_path
from channels.auth import AuthMiddlewareStack
from channels.security.websocket import AllowedHostsOriginValidator, OriginValidator
from chat.consumers import ChatConsumer
application = ProtocolTypeRouter({
'websocket':AllowedHostsOriginValidator(
AuthMiddlewareStack(
URLRouter(
[
url(r"^messages/(?P<username>[\w.@+-]+)/$", ChatConsumer),
]
)
)
)
})
我在这里回答是为了让事情更进一步。非常感谢您花时间添加 WebSocket URL 模式,我相信问题只是拼写错误。
把websocket_recieve
改成websocket_receive
就可以收到了
这些通道使用函数 _
转换为真正的套接字层的原因 websocket.receive
所以拼写很重要。