我有一个配置的情况,我完全不知道为什么它不工作。
我的测试代码存在websocket连接超时的问题: WebSocket network error: The operation couldn’t be completed. Operation timed out
如果部署的websocket配置没有响应,我可能在配置中出错了什么?
以下是我的关键配置:
设置.py
ASGI_APPLICATION = 'tracking.routing.application'
use_websockets = True
CHANNEL_LAYERS = {
"default": {
"BACKEND": "channels_redis.core.RedisChannelLayer",
"CONFIG": {
"hosts": [("redis://:password@127.0.0.1:6379/0")],
},
},
}
消费者.py
from django.contrib.auth.models import User
from channels.generic.websocket import WebsocketConsumer, AsyncWebsocketConsumer
from channels.consumer import AsyncConsumer
from channels.db import database_sync_to_async
import json, asyncio
class TestConsumer(AsyncWebsocketConsumer):
async def websocket_connect(self, event):
print("connected", event)
await self.send({
"type": "websocket.accept"
})
await asyncio.sleep(5)
await self.send({
"type": "websocket.close"
})
.html文件
<script>
var loc = window.location
console.log(loc)
var path = '/ws/channels-test/'
var wsStart = 'wss://'
var port = ':6379'
var endpoint = wsStart + loc.host + port + path
console.log(endpoint)
var socket = new WebSocket(endpoint)
socket.onmessage = function(e){
console.log("message", e)
}
socket.onopen = function(e){
console.log("open", e)
}
socket.onerror = function(e){
console.log("error", e)
}
socket.onclose = function(e){
console.log("close", e)
}
</script>
路由.py
from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter
from channels.security.websocket import AllowedHostsOriginValidator, OriginValidator
import trackinginterface.routing
application = ProtocolTypeRouter({
'websocket': AllowedHostsOriginValidator( #check an allowed domain is being used
AuthMiddlewareStack(
URLRouter(
trackinginterface.routing.websocket_urlpatterns
)
)
)
})
跟踪接口/routing.py
from django.urls import re_path
from . import consumers
websocket_urlpatterns = [
re_path(r'ws/channels-test/', consumers.TestConsumer),
]
apache2.conf文件
RewriteEngine on
RewriteCond %{HTTP:UPGRADE} ^WebSocket$ [NC,OR]
RewriteCond %{HTTP:CONNECTION} ^Upgrade$ [NC]
RewriteRule .* wss://127.0.0.1:6379%{REQUEST_URI} [P,QSA,L]
暂无答案!
目前还没有任何答案,快来回答吧!