I was doing a chat with django (backend) and react (frontend). 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. This morning it was working, but this afternoon, after having closed and reopened the 2 servers, it isn't working. 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:
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:
WebSocket HANDSHAKING /forums/divers/ [127.0.0.1:52726]
WebSocket DISCONNECT /forums/divers/ [127.0.0.1:52726]
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:
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. Can someone explain me why it's working in synchronous but not in asynchronous ?
我通过用AsyncWebsocketConsumer
替换WebsocketConsumer
解决了我的问题。
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.