简体   繁体   English

WebSocket 服务器拒绝 Django 频道中的所有连接

[英]WebSocket server refusing all connections in Django Channels

I was doing a chat with django (backend) and react (frontend).我正在与 django(后端)聊天并做出反应(前端)。 I use Django Channels to create the WebSocket server, but it isn't working : when trying to connect with React, it throws Forums.jsx:61 WebSocket connection to 'ws://localhost:8000/forums/divers/' failed: Error during WebSocket handshake: net::ERR_CONNECTION_RESET in the navigator console.我使用 Django Channels 创建 WebSocket 服务器,但它不起作用:尝试连接 React 时,它抛出Forums.jsx:61 WebSocket connection to 'ws://localhost:8000/forums/divers/' failed: Error during WebSocket handshake: net::ERR_CONNECTION_RESET导航器控制台中的Forums.jsx:61 WebSocket connection to 'ws://localhost:8000/forums/divers/' failed: Error during WebSocket handshake: net::ERR_CONNECTION_RESET This morning it was working, but this afternoon, after having closed and reopened the 2 servers, it isn't working.今天早上它可以工作,但是今天下午,在关闭并重新打开 2 个服务器后,它无法工作。 I only started a system to store the messages in the database during this time.这段时间我只启动了一个系统来将消息存储在数据库中。 The consumer:消费者:

from channels.generic.websocket import WebsocketConsumer
import json
from .models import Message

class ChatConsumer(WebsocketConsumer):
    async def connect(self):
        self.forum = self.scope["url_route"]["kwargs"]["forum"]

        # Join room group
        await self.channel_layer.group_add(
            self.forum,
            self.channel_name
        )
        print("connect func")
        self.accept()

    async def disconnect(self, close_code):
        await self.channel_layer.group_discard(
            self.forum,
            self.channel_name
        )

    async def receive(self, text_data=None, bytes_data=None):
        text_data_json = json.loads(text_data)
        message = text_data_json['message']
        print(message)
        await self.channel_layer.group_send(
            self.forum,
            {
                'type': 'chat_message',
                'message': message
            }
        )

    async def chat_message(self, event):
        message = event['message']
        #await sync_to_async(Message.objects.create)(message=message["message"], )
        # Send message to WebSocket
        await self.send(text_data=json.dumps({
            'message': message
        }))

opening of WebSocket client:开启 WebSocket 客户端:

class Forum extends Component { 
    constructor(props) {
        super(props)
        ...
        this.URL = constants.BACKEND_WS + "/forums/" + this.state.forum + "/";
        this.ws = new WebSocket(this.URL)
    }
    componentDidMount() {
        console.log("didmount");
        this.ws.onopen = () => {
            console.log('connected')
        };

        this.ws.onmessage = evt => {
            const message = JSON.parse(evt.data);
            console.log(message);
            this.addMessage(message)
        };

        this.ws.onclose = () => {
            console.log('disconnected');
            this.setState({
                ws: new WebSocket(this.URL),
            })
        }
    }
}

the logs of the django server: django 服务器的日志:

WebSocket HANDSHAKING /forums/divers/ [127.0.0.1:52726]
WebSocket DISCONNECT /forums/divers/ [127.0.0.1:52726]

mysite/routings.py : mysite/routings.py :

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

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

forums/routing.py:论坛/routing.py:

from django.urls import re_path

from . import consumers

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

If someone could explain me how to resolve this problem, he would really help me.如果有人可以向我解释如何解决这个问题,他真的会帮助我。


EDIT : When I remove async and replace await by async_to_sync , it works.编辑:当我删除async并用async_to_sync替换await ,它可以工作。 Can someone explain me why it's working in synchronous but not in asynchronous ?有人能解释一下为什么它在同步中工作而不是在异步中工作吗?

我通过用AsyncWebsocketConsumer替换WebsocketConsumer解决了我的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM