ConnectionResetError: [Errno 54] Connection reset by peer Django channels

Viewed 1807

enter image description hereshows connection reset error

path AnonymousUser

[28/Sep/2020 12:43:30] "GET /chat/aman/aman_indresh/ HTTP/1.1" 200 1920

path AnonymousUser

Not Found: /ws/chat/aman_indresh/

[28/Sep/2020 12:43:30] "GET /ws/chat/aman_indresh/ HTTP/1.1" 404 2211

Exception happened during processing of request from ('127.0.0.1', 54816) Traceback (most recent call last): File "/usr/local/Cellar/python@3.8/3.8.5/Frameworks/Python.framework/Versions/3.8/lib/python3.8/socketserver.py", line 650, in process_request_thread self.finish_request(request, client_address) File "/usr/local/Cellar/python@3.8/3.8.5/Frameworks/Python.framework/Versions/3.8/lib/python3.8/socketserver.py", line 360, in finish_request self.RequestHandlerClass(request, client_address, self) File "/usr/local/Cellar/python@3.8/3.8.5/Frameworks/Python.framework/Versions/3.8/lib/python3.8/socketserver.py", line 720, in init self.handle() File "/Users/indresh/Documents/Projects/tiktok/server/env/lib/python3.8/site-packages/django/core/servers/basehttp.py", line 174, in handle self.handle_one_request() File "/Users/indresh/Documents/Projects/tiktok/server/env/lib/python3.8/site-packages/django/core/servers/basehttp.py", line 182, in handle_one_request self.raw_requestline = self.rfile.readline(65537)

File "/usr/local/Cellar/python@3.8/3.8.5/Frameworks/Python.framework/Versions/3.8/lib/python3.8/socket.py", line 669, in readinto return self._sock.recv_into(b)

ConnectionResetError: [Errno 54] Connection reset by peer

Consumers.py

import json
from asgiref.sync import async_to_sync
from channels.generic.websocket import WebsocketConsumer

class ChatConsumer(WebsocketConsumer):
    def connect(self):
        # print(self.channel_layer)
        self.room_name = self.scope['url_route']['kwargs']['room_name']
        self.room_group_name = 'chat_%s' % self.room_name

        # Join room group
        async_to_sync(self.channel_layer.group_add)(
            self.room_group_name,
            self.channel_name
        )

        self.accept()

    def disconnect(self, close_code):
        # Leave room group
        async_to_sync(self.channel_layer.group_discard)(
            self.room_group_name,
            self.channel_name
        )

    # Receive message from WebSocket
    def receive(self, text_data):
        text_data_json = json.loads(text_data)
        message = text_data_json['message']
        sender_name = text_data_json['sender_name']

        # Send message to room group
        async_to_sync(self.channel_layer.group_send)(
            self.room_group_name,
            {
                'type': 'chat_message',
                'message': message,
                'sender_name': sender_name
            }
        )

    # Receive message from room group
    def chat_message(self, event):
        message = event['message']
        sender_name = event['sender_name']

        # Send message to WebSocket
        self.send(text_data=json.dumps({
            'message': message,
            'sender_name': sender_name

        }))

routing.py

from django.urls import re_path

from . import consumers

websocket_urlpatterns = [
    re_path(r'ws/chat/(?P<room_name>\w+)/$', consumers.ChatConsumer),
]

project- level routing.py

from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter
import chat_socket.routing

application = ProtocolTypeRouter({
    'websocket': AuthMiddlewareStack(
        URLRouter(
            chat_socket.routing.websocket_urlpatterns
        )
    ),
})

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>
    <input id="chat-message-submit" type="button" value="Send">
    {{ room_name|json_script:"room-name" }}
    {{ your_name|json_script:"your-name" }}
    <h2>{{your_name}}</h2>
    <script>
        const roomName = JSON.parse(document.getElementById('room-name').textContent);
        const yourName = JSON.parse(document.getElementById('your-name').textContent);

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

        chatSocket.onmessage = function(e) {
            const data = JSON.parse(e.data);
            console.log(e);
            document.querySelector('#chat-log').value += (data.sender_name+": "+data.message + '\n');
        };

        chatSocket.onclose = function(e) {
            console.log(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.querySelector('#chat-message-submit').click();
            }
        };

        document.querySelector('#chat-message-submit').onclick = function(e) {
            const messageInputDom = document.querySelector('#chat-message-input');
            const message = messageInputDom.value;
            chatSocket.send(JSON.stringify({
                'message': message,
                'sender_name': yourName,
            }));
            messageInputDom.value = '';
        };
    </script>
</body>
</html>

index.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8"/>
    <title>Chat Rooms</title>
</head>
<body>
    Your Name?<br>
    <input id="your-name-input" type="text" size="100"><br>
    Your chat room name?<br>
    <input id="room-name-input" type="text" size="100"><br>
    <input id="room-name-submit" type="button" value="Enter">

    <script>
        document.querySelector('#room-name-input').focus();
        document.querySelector('#room-name-input').onkeyup = function(e) {
            if (e.keyCode === 13) {  // enter, return
                document.querySelector('#room-name-submit').click();
            }
        };

        document.querySelector('#room-name-submit').onclick = function(e) {
            var roomName = document.querySelector('#room-name-input').value;
            var yourName = document.querySelector('#your-name-input').value;
            if(yourName == null){
                yourName = Math.floor(Math.random() * 100000000);
            }
            window.location.pathname = '/chat/' + yourName + '/' + roomName + '/';
        };
    </script>
</body>
</html>
0 Answers
Related