[英]Django chat app: WebSocket connection to wss://... failed
我有一個即時聊天應用程序在我的 localhost 上成功運行,但是在部署到 Heroku 之后,我收到了一個錯誤,因為我使用的是ws
而不是wss
。
我在下面的 room.html 中更改了它,但現在我遇到了一個非常普遍的錯誤:
WebSocket connection to 'wss://game-exchange-ca.herokuapp.com/ws/chat/room_name/' failed:
,它指向我的 javascript 文件reconnecting_websockets.js
。 在 Heroku 日志中,我得到: Not Found: /ws/chat/room_name/
。 對於這個看似常見的問題,有很多建議的解決方案,但沒有一個對我有用。
我在 heroku 上安裝了 redis 並確保它正常工作。 下面是我的代碼:
Procfile ~~~編輯:我現在使用 DAPHNE 而不是 GUNICORNE,但它導致我的應用程序崩潰,我無法弄清楚為什么,有人知道我是否必須在這里使用 USE DAPHNE?~~~
# web: gunicorn django_project.wsgi --log-file - # OLD
release: python manage.py migrate #NEW
web: daphne django_project.asgi:start_app --port $PORT --bind 0.0.0.0 -v2
worker: python manage.py runworker -v2
asgi.py
import os
from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter
from django.core.asgi import get_asgi_application
import chat.routing
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "django_project.settings")
application = ProtocolTypeRouter({
"http": get_asgi_application(), # TODO: CONFIRM
"websocket": AuthMiddlewareStack(
URLRouter(
chat.routing.websocket_urlpatterns
)
),
})
路由.py
from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter
import chat.routing
application = ProtocolTypeRouter({
# (http->django views is added by default)
'websocket': AuthMiddlewareStack(
URLRouter(
chat.routing.websocket_urlpatterns #references urls defined in chat/routing.py
)
),
})
wsgi.py
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'django_project.settings')
application = get_wsgi_application()
settings.py(相關部分)
# ~~~MESSAGES CONFIG~~~
WSGI_APPLICATION = 'django_project.wsgi.application'
ASGI_APPLICATION = 'django_project.asgi.application' # older version of django: 'django_project.routing.application'
# Channels redis config:
CHANNEL_LAYERS = {
'default': {
'BACKEND': 'channels_redis.core.RedisChannelLayer',
'CONFIG': {
"hosts": ['rediss://:p628bf20dab326cedb30d4df129e9691dbb6e7e1f4486954eadbfdf77db854369@ec2-34-235-242-69.compute-1.amazonaws.com:25180'], #todo: confirm. Changed from "127.0.0.1" to 'redis'... found promising answer, changing this
},
},
}
CACHES = {
"default": {
"BACKEND": "redis_cache.RedisCache",
"LOCATION": os.environ.get('REDIS_URL'),
"OPTIONS": {
"CONNECTION_POOL_KWARGS": {
"ssl_cert_reqs": False
}
}
}
}
房間.html
{% load static %}
<!DOCTYPE html>
<html>
<head>
<link href='https://fonts.googleapis.com/css?family=Source+Sans+Pro:400,600,700,300' rel='stylesheet' type='text/css'>
<script src="https://use.typekit.net/hoy3lrg.js"></script>
<link rel='stylesheet prefetch' href='https://cdnjs.cloudflare.com/ajax/libs/meyer-reset/2.0/reset.min.css'>
<link rel='stylesheet prefetch' href='https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.6.2/css/font-awesome.min.css'>
<link href="//maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="//maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<link href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="//netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
</head>
<body>
<div class="messages">
<ul id="chat-log">
</ul>
<div class="message-input">
<div class="wrap">
<input id="chat-message-input" type="text" placeholder="Write your message..." />
<button id="chat-message-submit" class="submit">
<i class="fa fa-paper-plane" aria-hidden="true"></i>
</button>
</div>
</div>
</div>
<script src="{% static '/reconnecting_websockets.js' %}"></script>
<script>
var roomName = {{ room_name_json }};
var username = {{ user }};
var chatSocket = new ReconnectingWebSocket( //todo: REMOVE wss as its breaking the app locally... S.O. said make 1st wss, and 2nd ws
'ws://' + window.location.host + //changed from 'ws://' to 'wss://'
'/ws/chat/' + roomName + '/');
chatSocket.onopen = function(e) {
fetchMessages();
}
chatSocket.onmessage = function(e) {
var data = JSON.parse(e.data);
if (data['command'] === 'messages') {
for ( i = data['messages'].length-1; i>=0; i--) {
createMessage(data['messages'][i]);
}
} else if (data['command'] === 'new_message'){
createMessage(data['message']);
}
};
chatSocket.onclose = function(e) {
console.error('Chat socket closed unexpectedly');
};
document.querySelector('#chat-message-input').onkeyup = function(e) {
if (e.keyCode === 13) { // enter, return
document.querySelector('#chat-message-submit').click();
}
};
document.querySelector('#chat-message-submit').onclick = function(e) {
var messageInputDom = document.getElementById('chat-message-input');
var message = messageInputDom.value;
chatSocket.send(JSON.stringify({
'command': 'new_message',
'message': message,
'from': username
}));
messageInputDom.value = '';
};
function fetchMessages() {
chatSocket.send(JSON.stringify({'command': 'fetch_messages' }));
}
function createMessage(data) {
var author = data['author'];
document.getElementById('chat-log').innerHTML += '<b>' + author + '</b>: ' + data.content + '<br />';
}
</script>
</body>
</html>
如果你使用 wss,你的主機必須是 https。
如果你設置Debug=False,你應該使用daphne;
pip 安裝達芙妮
pip 安裝-U Twisted[tls,http2]
須藤 vim /etc/systemd/system/daphne.service
[Unit]
Description=daphne daemon
After=network.target
[Service]
User=centos
Group=nginx
WorkingDirectory=/var/www/project_path
ExecStart=/path/daphne -u /project_path/tmp/channels.sock project_name.asgi:application
[Install]
WantedBy=multi-user.target
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.