使用 Django Channels 的实时聊天应用程序

发布于 2025-01-15 20:21:17 字数 4605 浏览 1 评论 0原文

我的实时聊天应用程序拒绝发送消息。完全没有错误。 我尝试通过在经过的每个阶段登录到控制台来跟踪错误,并尝试打印到终端。

我认为问题可能来自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,
        }))

这里是我的room.html:

{% 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() 甚至没有收到消息。但任何地方都没有显示错误。

My real time chat application refuses to send message. no errors at all.
I have tried tracing the errors by logging to the console at every stage passed and also tried printing to the terminal.

I think the problem might be from consumers.py

here is my 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,
        }))

Here is my room.html:

{% 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 %}

When a message is sent. nothing happens, my chatSocket.onmessage() doesn't even recieve the message. yet no error is displayed anywhere.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

丢了幸福的猪 2025-01-22 20:21:17

我发现了这个错误。

这都是因为我拼错了 receive。

async def recieve(self, text_data):

而不是:

async def receive(self, text_data):

I found the bug.

it's all because I misspelt receive.

async def recieve(self, text_data):

instead of:

async def receive(self, text_data):
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文