![](/img/trans.png)
[英]Python Django Channels - Is better to isolate the WebSocket Server?
[英]WebSocket server refusing all connections in Django Channels
我正在與 django(后端)聊天並做出反應(前端)。 我使用 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
。 今天早上它可以工作,但是今天下午,在關閉並重新打開 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
)
),
})
論壇/routing.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
解決了我的問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.