【发布时间】:2021-07-15 08:05:53
【问题描述】:
我正在尝试在 django 项目中使用 daphne 来处理 websocket 连接。我已经安装了 daphne,它似乎正在运行。但是,我无法发送任何 websocket 连接请求。这是我的 daphne.service 文件:
[Unit]
Description=WebSocket Daphne Service
After=network.target
[Service]
Type=simple
User=root
WorkingDirectory=/home/django/AysleServer/src
ExecStart=/home/django/AysleServer/MyEnv/bin/python /home/django/AysleServer/MyEnv/bin/daphne -e ssl:8001:privateKey=/etc/letsencrypt/live/djangoadmin.aysle.tech/privk>
Restart=on-failure
[Install]
WantedBy=multi-user.target
在检查达芙妮的日志时,它显示:
Started WebSocket Daphne Service.
Starting server at ssl:8001:privateKey=/etc/letsencrypt/live/djangoadmin.aysle.tech/privk...>
HTTP/2 support not enabled (install the http2 and tls Twisted extras)
Configuring endpoint ssl:8001:privateKey=/etc/letsencrypt/live/djangoadmin.aysle.tech/pri...>
Listening on TCP address 0.0.0.0:8001
我认为是 http2 和 tls 导致了问题,因此尝试使用以下命令将它们安装在我的虚拟环境中:
pip install -U 'Twisted[tls,http2]'
但它们已经出现了,如下所示:
Requirement already satisfied: Twisted[http2,tls] in /usr/lib/python3/dist-packages (18.9.0)
Requirement already satisfied: idna!=2.3,>=0.6 in /usr/lib/python3/dist-packages (from Twisted[http2,tls]) (2.8)
Requirement already satisfied: pyopenssl>=16.0.0 in /usr/lib/python3/dist-packages (from Twisted[http2,tls]) (19.0.0)
Requirement already satisfied: service_identity in /usr/lib/python3/dist-packages (from Twisted[http2,tls]) (18.1.0)
Requirement already satisfied: h2<4.0,>=3.0 in /usr/local/lib/python3.8/dist-packages (from Twisted[http2,tls]) (3.2.0)
Requirement already satisfied: priority<2.0,>=1.1.0 in /usr/local/lib/python3.8/dist-packages (from Twisted[http2,tls]) (1.3.0)
Requirement already satisfied: hpack<4,>=3.0 in /usr/local/lib/python3.8/dist-packages (from h2<4.0,>=3.0->Twisted[http2,tls]) (3.0.0)
Requirement already satisfied: hyperframe<6,>=5.2.0 in /usr/local/lib/python3.8/dist-packages (from h2<4.0,>=3.0->Twisted[http2,tls]) (5.2.0)
我正在使用 Gunicorn 来处理 http 请求,它按预期工作。这是我的 asgi.py 文件
import os
import django
from channels.routing import get_default_application
from decouple import config
os.environ.setdefault("DJANGO_SETTINGS_MODULE", f'{config("PROJECT_NAME")}.settings')
django.setup()
application = get_default_application()
这是我的 routing.py 文件:
from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter
from channels.security.websocket import AllowedHostsOriginValidator
from django.urls import path
from wsocket.consumers import *
ws_patterns = [
path('ws/order/', OrderConsumer.as_asgi()),
]
application = ProtocolTypeRouter({
'websocket' : AllowedHostsOriginValidator(
AuthMiddlewareStack(
URLRouter(ws_patterns)
)
)
})
我尝试通过以下方式发送 websocket 请求:
wss://djangoadmin.aysle.tech:8001/ws/order/
wss://djangoadmin.aysle.tech/ws/order/
但我无法连接。请帮助我我哪里出错了。提前感谢您的时间。
【问题讨论】: