确保您的EC2实例安全组中打开了所需的端口(例如,端口8000)
确保您在您的Django Channels应用程序中正确地配置并运行了ASGI服务器。例如,在您的项目的settings.py文件中添加以下代码:
ASGI_APPLICATION = 'myproject.routing.application'
import os
from django.core.asgi import get_asgi_application
from channels.routing import ProtocolTypeRouter, URLRouter
from channels.auth import AuthMiddlewareStack
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings')
application = ProtocolTypeRouter({
'http': get_asgi_application(),
'websocket': AuthMiddlewareStack(
URLRouter(
myproject.routing.websocket_urlpatterns
)
),
})
CHANNEL_LAYERS = {
"default": {
"BACKEND": "channels.layers.InMemoryChannelLayer"
# or "BACKEND": "channels.layers.RedisChannelLayer",
# "CONFIG": {"hosts": [("127.0.0.1", 6379)]},
},
}
var ws_scheme = window.location.protocol == "https:" ? "wss" : "ws";
var ws_path = ws_scheme + '://' + window.location.host + "/mywebsocket/";
var socket = new WebSocket(ws_path);
socket.onmessage = function(event) {
console.log("Received message: " + event.data);
};
CHANNEL_LAYERS = {
"default": {
"BACKEND": "channels.layers.InMemoryChannelLayer",
"ROUTING": "myapp.routing.websocket_routing",
"CONFIG": {
"channel_capacity": {"example_channel": 10},
"channel_layer:verbosity": "debug",
},
},
}
使用上述步骤中的任何一个或组合,您应该能够成功连接到您的Django Channels应用程序的WebSocket连接。