使用安全 WebSocket 连接的 Django 通道 - WSS://

Django channels using secured WebSocket connection - WSS://

当我尝试使用 sslserver 运行 Django 应用程序时,如下所示,

python manage.py runsslserver

错误:

回溯:

Validating models...

System check identified no issues (0 silenced).
November 08, 2019 - 11:17:26
Django version 2.0.7, using settings 'dashboard_channels.settings'
Starting development server at https://127.0.0.1:8000/
Using SSL certificate: \lib\site-packages\sslserver\certs\development.crt
Using SSL key: \lib\site-packages\sslserver\certs\development.key
Quit the server with CTRL-BREAK.
[08/Nov/2019 11:18:33] "GET / HTTP/1.1" 200 1299
[08/Nov/2019 11:18:34] "GET / HTTP/1.1" 200 1299
[08/Nov/2019 11:18:35] "GET /static/js/jquery.js HTTP/1.1" 200 270575
Not Found: /ws/home
[08/Nov/2019 11:18:36] "GET /ws/home HTTP/1.1" 404 2134

浏览器控制台:

(index):31 WebSocket connection to 'wss://127.0.0.1:8000/ws/home' failed: Error during WebSocket handshake: Unexpected response code: 404
(index):41 error Event
(index):44 close CloseEvent

代码:

Javascript:

 var loc = window.location;
 var wsStart = 'ws://';
 if (loc.protocol == 'https:') {
     wsStart = 'wss://'
 }
 var endpoint = wsStart + loc.host + '/ws/home';

 var socket = new WebSocket(endpoint);

它在 python manage.py runserver 命令下工作正常,这意味着 http 它在工作但在 https 上不工作。

如何解决这个问题? (如何调试解决这个问题?)

是否有任何其他方法可以在 https 门户上部署 WebSockets?

仍然面临这个问题。有人可以帮忙吗?

总之这是为了测试目的,最后,我需要将它部署在windows服务器机器上的Apache2.4上。我已经为 https 设置但没有为网络套接字设置的地方。

我找到了答案,runserver 命令正确检测了 asgi.py 文件和 运行 使用 daphne 的 WebSockets 上的 Django 通道应用程序。不知何故 runsslserver 没有做同样的工作,它是 运行 宁 wsgi.py 文件而不是 asgi.py 文件。

阅读不同的方法后,我了解到我们可以使用我们的普通开发服务器(即使用 wsgi.py 文件)处理 HTTPS 请求,使用 wss 请求 Daphne(即,使用 asgi.py 文件)。

Daphne 是一个官方设计的服务器来处理 django-channels(建立在 twisted 模块的顶部)。

所以,最后,我们需要运行两台服务器分别处理httpswss

# In command prompt 1 (For production, use Apache or Nginx to serve HTTP requests)
python manage.py runsslserver 0.0.0.0:8000

# In command prompt 2 (This works for production as well).
daphne -e ssl:8001:privateKey=cert\private.pem:certKey=cert\public.pem real_time_table.asgi:application

We should use the same SSL certificates used by runsslserver for testing.

最后,在JavaScript:

var loc = window.location;
var wsStart = 'ws://';
if (loc.protocol == 'https:') {
     wsStart = 'wss://'
}
// var endpoint = wsStart + 'your_ip_address:port_given_to_daphne_server' + '/ws/home';
// For above command, it look like this
var endpoint = wsStart + 'xxx.xx.xx.xxx:8001' + '/ws/home';
// Note the websocket port is 8001
var socket = new WebSocket(endpoint);

我希望,这会节省一些人的时间。