我在 django 应用程序中建立 websockets 连接时遇到问题。 这是错误消息
WebSocket connection to 'ws://127.0.0.1:8000/chat/' failed:
我的javascript文件
let loc = window.location
let wsStart = 'ws://'
if(loc.protocol === 'https:') {
wsStart = 'wss://'
}
let endpoint = wsStart + window.location.host + loc.pathname;
var socket = new WebSocket(endpoint)
socket.onopen = async function(e){
console.log('open', e)
}
socket.onmessage = async function(e){
console.log('message', e)
}
路由.py
websocket_urlpatterns = [
path('ws/chat/', consumers.ChatConsumer.as_asgi()),
]
我能够通过更改我的 asgi.py 文件来解决它
"""
ASGI config for social_book project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/4.1/howto/deployment/asgi/
"""
import os
import chatapp.routing
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', 'social_book.settings')
application = ProtocolTypeRouter({
'http': get_asgi_application(),
'websocket': AuthMiddlewareStack({
URLRouter(
chatapp.routing.websocket_urlpatterns
)
})
})
至
"""
ASGI config for social_book project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/4.1/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
from channels.routing import ProtocolTypeRouter, URLRouter
from channels.auth import AuthMiddlewareStack
from chatapp.routing import websocket_urlpatterns
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'social_book.settings')
application = ProtocolTypeRouter({
'http': get_asgi_application(),
'websocket': AuthMiddlewareStack(
URLRouter(
websocket_urlpatterns
)
)
})
messages.js
const loc = window.location;
const wsStart = loc.protocol === 'https:' ? 'wss://' : 'ws://';
const endpoint = wsStart + loc.host + '/ws/chat/';
const socket = new WebSocket(endpoint);
socket.onopen = function (event) {
console.log('WebSocket connection opened:', event);
};
socket.onmessage = function (event) {
console.log('WebSocket message received:', event);
// Handle incoming messages as needed
};
socket.onerror = function (event) {
console.error('WebSocket error:', event);
};
socket.onclose = function (event) {
console.log('WebSocket connection closed:', event);
};