我有一个 Django 项目,在我的 Mac 上本地运行。 我使用通道来创建 websocket 连接。
有趣的事情发生了: 当我尝试通过 .html 文件连接时,网络套接字可以工作:
myTemplate.html
const ws = new WebSocket(
'ws://'
+ window.location.host
+'/ws/test/?token='
+'**mytoken**'
);'
我可以发送和接收消息。 但相同的 URL 在邮递员或 https://websocketking.com/
中不起作用首先,我认为这是因为我在本地运行服务器。 但在真实服务器上也存在同样的问题。
我可以从 html 页面创建聊天,但无法从“外部”连接。
我搜索了所有 stackoverflow 并实现了所有内容 - 无济于事。
asgi.py
import os
import django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'spacetime.settings.dev')
django.setup()
from channels.routing import ProtocolTypeRouter,get_default_application
from channels.auth import AuthMiddlewareStack
from channels.security.websocket import AllowedHostsOriginValidator
from channels.routing import ProtocolTypeRouter, URLRouter
from django.core.asgi import get_asgi_application
from django.urls import path, re_path
from django_channels_jwt_auth_middleware.auth import JWTAuthMiddlewareStack
from myapp import consumers, routing
application = ProtocolTypeRouter({
'http': get_asgi_application(),
'websocket': AllowedHostsOriginValidator(
JWTAuthMiddlewareStack(
URLRouter(
routing.websocket_urlpatterns
)
)
),
})
设置
ASGI_APPLICATION = 'spacetime.asgi.application'
CHANNEL_LAYERS = {
"default": {
"BACKEND": "channels_redis.core.RedisChannelLayer",
"CONFIG": {
"hosts": [("localhost", 6379)],
},
},
}
INSTALLED_APPS = [
'daphne',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
***
]
vccode控制台
Django version 4.1.2, using settings 'spacetime.settings.dev'
Starting ASGI/Daphne version 4.0.0 development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
从 html 文件连接时的 vccode 控制台
HTTP GET /my/socket/view/ 200 [0.01, 127.0.0.1:60258]
WebSocket HANDSHAKING /ws/test/ [127.0.0.1:60260]
WebSocket CONNECT /ws/test/ [127.0.0.1:60260]
连接时的 xccode 控制台
WebSocket HANDSHAKING /ws/test/ [127.0.0.1:60759]
WebSocket REJECT /ws/test/ [127.0.0.1:60759]
WebSocket DISCONNECT /ws/test/ [127.0.0.1:60759]
邮递员
Request URL: http://127.0.0.1:8000/ws/test/?token=**mytoken**
Request Method: GET
Status Code: 403 Access denied
Request Headers
Sec-WebSocket-Version: 13
Sec-WebSocket-Key: 0VRmdvoFhma7lndljwIY6w==
Connection: Upgrade
Upgrade: websocket
Sec-WebSocket-Extensions: permessage-deflate; client_max_window_bits
Host: 127.0.0.1:8000
Response Headers
代币没问题
Could not connect to "ws://127.0.0.1:8000/ws/test/?token=**mytoken**". You may be able to find more information using Inspector/Dev Tools on this page.
Connecting to ws://127.0.0.1:8000/ws/test/?token=**mytoken**
有什么想法为什么它不能与邮递员一起使用吗?
我不知道它是否会有所不同,但尝试使你的channel_layers配置为
CHANNEL_LAYERS = {
"default": {
"BACKEND": "channels_redis.core.RedisChannelLayer",
"CONFIG": {
"hosts": [("127.0.0.1", 6379)],
},
},
}
我必须使用“OriginValidator”代替“AllowedHostsOriginValidator”并设置有效域的列表。 这里