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

sha*_*eed 12 javascript python ssl wss websocket

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

python manage.py runsslserver
Run Code Online (Sandbox Code Playgroud)

错误:

追溯:

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
Run Code Online (Sandbox Code Playgroud)

浏览器控制台:

(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
Run Code Online (Sandbox Code Playgroud)

代码:

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);
Run Code Online (Sandbox Code Playgroud)

它与python manage.py runserver命令一起工作正常,意味着http它可以工作但不能与https.

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

还有其他方法可以在https门户上部署 WebSockets吗?

还是面临这个问题。有人可以帮忙吗?

无论如何,这是出于测试目的,最后,我需要将其部署在 Windows 服务器机器上的 Apache2.4 上。我已经https为 Web 套接字设置但没有设置的地方。

sha*_*eed 8

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

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

Daphne 是一个官方设计的服务器,用于处理 django-channels(建立在扭曲模块的顶部)。

所以,最后,我们需要运行两个服务器来处理https,并wss分别。

# 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
Run Code Online (Sandbox Code Playgroud)

我们应该使用runsslserver用于测试的相同 SSL 证书。

最后,在 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);
Run Code Online (Sandbox Code Playgroud)

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