简体   繁体   中英

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]

error given

  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.

Intention

My intention was for me to send a message to via the socket from the thread.html in under the method socket.onopen but I always receive an error message saying that the raise ValueError("No handler for message type %s" % message["type"]

socket urlpattern

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),
                ]
            )
        )
    )
})

I'm answering here to take things further. Thank you so much for taking the time to add WebSocket URL patterns and I believe the problem is just with the spelling mistake.

Change the websocket_recieve to websocket_receive and it can able to receive the message.

The reason for these channels using function _ to convert into real socket layer websocket.receive so spelling is important.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM