我正在与django(后端(和react(前端(聊天。我使用Django Channels创建WebSocket服务器,但它不起作用:当尝试连接React时,它会抛出导航器控制台中的Forums.jsx:61 WebSocket connection to 'ws://localhost:8000/forums/divers/' failed: Error during WebSocket handshake: net::ERR_CONNECTION_RESET
。今天早上它还在工作,但今天下午,在关闭并重新打开2台服务器后,它就不工作了。在此期间,我只启动了一个将消息存储在数据库中的系统。消费者:
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
}))
打开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),
})
}
}
}
django服务器的日志:
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
)
),
})
论坛/路由.py:
from django.urls import re_path
from . import consumers
websocket_urlpatterns = [
re_path(r'forums/(?P<forum>w+)/$', consumers.ChatConsumer),
]
如果有人能向我解释如何解决这个问题,他真的会帮助我
编辑:当我删除async
并用async_to_sync
替换await
时,它就工作了。有人能解释一下为什么它以同步方式工作而不以异步方式工作吗?
我通过用AsyncWebsocketConsumer
替换WebsocketConsumer
来解决问题。