websocket 使用Django频道的真实的聊天应用程序

dced5bon  于 2022-11-24  发布在  Go
关注(0)|答案(1)|浏览(191)

我的真实的聊天应用程序拒绝发送消息。完全没有错误。我已经尝试通过在每个阶段登录到控制台来跟踪错误,还尝试打印到终端。
我认为问题可能来自consumers.py

这里是我的consummers.py

import json
from channels.generic.websocket import AsyncWebsocketConsumer
from asgiref.sync import sync_to_async

class ChatConsumer(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_name, 
            self.channel_name,
        )
        await self.accept()

    async def disconnect(self):
        print('\nOguh... disconnecting\n')
        await self.channel_layer.group_discard(
            self.room_group_name,
            self.channel_name
        )
    
    async def recieve(self, text_data):
        data = json.loads(text_data)
        message = data['message']
        username = data['username']
        room = data['room']
        print('\nOguh... recieving a message\n')

        await self.channel_layer.group_send(
            self.room_group_name,
            {
                'type': 'chat_message',
                'message': message,
                'username': username,
                'room': room
            }
        )

    async def chat_message(self, event):
        print('\nOguh... Chat message\n')
        message = event['message']
        username = event['username']
        room = event['room']
        await self.send(text_data=json.dumps({
            'message': message,
            'username': username,
            'room': room,
        }))

这是我的房间

{% extends 'core/base.html' %}

{% block tittle %} {{ room.name }} | {% endblock %}


{% block content %}

<div class="p-10 lg:p-20 text-center">
    <h1 class="text-3xl lg:text-6xl text-white">{{ room.name }}</h1>
</div>
<div class="lg:w-2/4 mx-4 lg:mx-auto p-4 bg-white rounded-xl">
    <div class="chat-messages space-y-3" id='chat-messages'>

        <div class="p-4 bg-gray-200 rounded-xl">
            <p class='front-semibold'>Username</p>
            <p> A sample message</p>
        </div>
        
    </div>
</div>

<div class="lg:w-2/4 mx-4 lg:mx-auto p-4 bg-white rounded-xl">
    <form method='POST' action='.' class='flex'>
        <input type='text' name='content' class='flex-1 mr-3' placeholder='Your message here' id='chat-meesage-input'>
        <button type= 'button' class='px-5 py-3 rounded-xl text-white bg-teal-600 hover:bg-teal-700'
        id='chat-message-submit'>
        Submit</button>
    </form>
</div>

{% endblock %}

{% block script %}

{{room.slug|json_script:"json-roomname"}}
{{request.user.username|json_script:"json-username"}}
 <script>
    
    const roomName = JSON.parse(document.getElementById('json-roomname').textContent)
    const userName = JSON.parse(document.getElementById('json-username').textContent)

    const chatSocket = new WebSocket(
        'ws://'
        + window.location.host
        + '/ws/'
        + roomName
        + '/'
    );

    chatSocket.onmessage = function(e){
        console.log('There is a message')
        const data = JSON.parse(e.data)
        if(data.message){
            let html = '<div class="p-4 bg-gray-200 rounded-xl">';
                html += "<p class='front-semibold'>" + data.username + '</p>';
                html += '<p>' + data.message +'</p></div>';
            document.querySelector('#chat-messages') += html;
        }else{
            alert('empty message box!')
        }
    }
    chatSocket.onclose = function(e){
        console.log("chat socket closed")
        console.error("chat socket closed")
    }

    document.querySelector('#chat-message-submit').onclick = function(e){
        console.log('clicked the submit button')
        e.preventDefault();
        console.log('preventDefault stage passed')
        const messageInputDom = document.querySelector('#chat-meesage-input');
        const message = messageInputDom.value;
        console.log('message value collected')

        chatSocket.send(JSON.stringify({
            'message': message,
            'username': userName,
            'room': roomName
        }))
        messageInputDom.value = ''
        return false;
    };
 </script>
{% endblock %}

当一个消息被发送。什么也没有发生,我的chatSocket.onmessage()甚至没有收到消息。但没有错误显示任何地方。

6tr1vspr

6tr1vspr1#

我找到窃听器了。
都是因为我把receive拼错了。

async def recieve(self, text_data):

而不是:

async def receive(self, text_data):

相关问题