我正在设置一个具有聊天室系统的Web应用程序。我最初在这里遵循了该教程:https://channels.readthedocs.io/en/latest/tutorial/index.html
它在开发中可以完美地工作,但是在部署应用程序时,我必须使用daphne使其正常工作,因为我使用的是Apache。
sudo daphne -b 0.0.0.0 -p 81 myapp.asgi:application
但是当我使用certbot获取https的ssl证书时,每当尝试发送消息时,我都会开始收到以下控制台错误:
Mixed Content: The page at: https://example.com/home/chat/46508f6fc17b04ad04ba0e8e5095e4b233944ed3d4145e5501ada21bab7042c6/' was loaded over HTTPS, but attempted to connect to the insecure WebSocket endpoint 'ws://example.com:81/ws/chat/46508f6fc17b04ad04ba0e8e5095e4b233944ed3d4145e5501ada21bab7042c6/'. This request has been blocked; this endpoint must be available over WSS.
我的第一个想法是从以下位置更改room.html中的javascript:
var chatSocket = new WebSocket(
'ws://' + window.location.host +
':81/ws/chat/' + roomName + '/');
对此:
var chatSocket = new WebSocket(
'wss://' + window.location.host +
':81/ws/chat/' + roomName + '/');
这不起作用,当我尝试发送消息时导致以下错误:
(index):150 Uncaught DOMException: Failed to execute 'send' on 'WebSocket': Still in CONNECTING state.
mysite-le-ssl.config:
<VirtualHost *:443>
ServerName www.example.com
ServerAdmin webmaster@localhost
DocumentRoot /var/www/html
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
<Directory /home/me/myproject/myapp>
<Files wsgi.py>
Require all granted
</Files>
</Directory>
WSGIScriptAlias / /home/me/myproject/myapp/wsgi.py
WSGIDaemonProcess my-app python-path=/home/me/myproject python-home=/home/me/myproject/venv
WSGIProcessGroup kalos-app
Include /etc/letsencrypt/options-ssl-apache.conf
ServerAlias mydomain.com
SSLCertificateFile /etc/letsencrypt/live/example.com-0001/fullchain.pem
SSLCertificateKeyFile /etc/letsencrypt/live/example.com-0001/privkey.pem
</VirtualHost>
</IfModule>
<IfModule mod_ssl.c>
<VirtualHost *:80>
ServerName example.com
Redirect permanent / http://www.example.com/
</VirtualHost>
</IfModule>
room.html(仅Websocket连接):
var roomName = {{ room_name_json }};
document.getElementById("chat-log").scrollTop = document.getElementById("chat-log").scrollHeight;
var chatSocket = new WebSocket(
'wss://' + window.location.host +
':81/ws/chat/' + roomName + '/');
routing.py:
from . import consumers
websocket_urlpatterns = [
url(r'^ws/chat/(?P<room_name>[^/]+)/$', consumers.ChatConsumer),
url(r'^wss/chat/(?P<room_name>[^/]+)/$', consumers.ChatConsumer),
(所有其他文件与本教程中的文件完全相同,但略有调整)