繁体   English   中英

Django 聊天应用程序:WebSocket 连接到 wss://... 失败

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM