简体   繁体   中英

Django-channels:chatSocket.onmessage or chatSocket.send does not work

I'm trying to implement a django channels chat app. when the submit button of the room view is clicked, the message does not appear in the chat log. which make me think that somethings wrong with chat.onmessage command, it does not seem to fire. can someone help me fix the issue. here is the code for room view:

<!-- chat/templates/room.html -->
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8"/>
    <title>Chat Room</title>
</head>
<body>
    <textarea id="chat-log" cols="100" rows="20"></textarea><br/>
    <input id="chat-message-input" type="text" size="100"/><br/>
    <button id="chat-message-submit" type="submit" value="Send">Send</button>
</body>z
<script>
    var roomName = {{ room_name_json }};
    var chatSocket = new WebSocket(
        'ws://' + window.location.host +
        '/ws/chat/' + roomName + '/');

    chatSocket.onmessage = function(e) {
        console.log("got to onmessage");
        var data = JSON.parse(e.data);
        var message = data['message'];
        document.getElementById('chat-log').value += (message + '\n');
    };

    chatSocket.onclose = function(e) {
        console.error('Chat socket closed unexpectedly');
    };

    document.querySelector('#chat-message-input').focus();
    document.querySelector('#chat-message-input').onkeyup = function(e) {
        if (e.keyCode === 13) {  // enter, return
            document.getElementById('chat-message-submit').click();
        }
    };

    document.getElementById('chat-message-submit').onclick = function(e) {
        var messageInputDom = document.getElementById('chat-message-input');
        var message = messageInputDom.value;
        console.log("got message : " + message);
        chatSocket.send(JSON.stringify({
            'message': message
        }));
        console.log("This was done?");
        messageInputDom.value = '';
    };
</script>
</html>

Here is my consumer view:

from channels.generic.websocket import WebsocketConsumer
import json

class ChatConsumer(WebsocketConsumer):
    def connect(self):
        self.accept()

    def disconnect(self, close_code):
        pass

    def recieve(self, text_data):
        text_data_json = json.loads(text_data)
        message = text_data_json['message']
        self.send(text_data = json.dumps({
            'message' : message
        }))

I'm so stupid I literally made a typo, used function name "received" instead of "recieved". Thanks I'll go cry in the corner now.

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