我正在尝试使用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在检查Daphne的日志时,它显示如下:
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/但是我不能连接。请帮帮我,我哪里错了?提前感谢您的宝贵时间。
发布于 2021-07-15 16:12:20
我认为,如果有任何东西没有被防火墙阻止或任何错误,检查/var/log/syslog可能会很有用。
这是在本地还是在服务器上?
https://stackoverflow.com/questions/68390104
复制相似问题