ConnectionResetError:[Errno 54]通过对等Django通道重置连接

时间:2020-09-28 13:00:31

标签: python django websocket django-channels

enter image description here 显示连接重置错误

路径AnonymousUser

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

路径AnonymousUser

未找到:/ ws / chat / aman_indresh /

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

在处理来自('127.0.0.1',54816)的请求期间发生异常 追溯(最近一次通话): 在process_request_thread中的第650行,文件“ /usr/local/Cellar/python@3.8/3.8.5/Frameworks/Python.framework/Versions/3.8/lib/python3.8/socketserver.py” self.finish_request(请求,客户地址) 在finish_request中的文件“ /usr/local/Cellar/python@3.8/3.8.5/Frameworks/Python.framework/Versions/3.8/lib/python3.8/socketserver.py”中,行360 self.RequestHandlerClass(请求,客户地址,自我) init 中的文件“ /usr/local/Cellar/python@3.8/3.8.5/Frameworks/Python.framework/Versions/3.8/lib/python3.8/socketserver.py”,第720行 self.handle() 文件“ /Users/indresh/Documents/Projects/tiktok/server/env/lib/python3.8/site-packages/django/core/servers/basehttp.py”,行174,在句柄中 self.handle_one_request() 文件“ /Users/indresh/Documents/Projects/tiktok/server/env/lib/python3.8/site-packages/django/core/servers/basehttp.py”,行182,在handle_one_request中 self.raw_requestline = self.rfile.readline(65537)

文件 “ /usr/local/Cellar/python@3.8/3.8.5/Frameworks/Python.framework/Versions/3.8/lib/python3.8/socket.py”,第669行,读入 返回self._sock.recv_into(b)

ConnectionResetError:[Errno 54]对等重置连接

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

项目级路由。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>

1 个答案:

答案 0 :(得分:-5)

我遇到了同样的问题 ConnectionResetError: [Errno 54] Connection reset by peer

问题是关于尝试通过带有 debug settings to False 的开发服务器提供静态文件,只有在设置文件中将 debug 设置为 True 时,开发服务器才能提供静态文件。

在您的设置文件中替换

DEBUG = False

DEBUG = True

现在重启你的开发服务器,它现在应该可以工作了。