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

15

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

python manage.py runsslserver

错误:

回溯(traceback):

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,但没有设置Web套接字。


1
它显示“未找到:/ws/home”。对于http,它是否也是这样? - ege
2
不,它正常工作。http没有问题。 - shaik moeed
1
@shaikmoeed 请检查您是否在settings.py中配置了CHANNEL_LAYERS。 - wowkin2
1
@wowkin2 CHANNEL_LAYERS已经配置好,并且在http上运行得非常好。如何在https上运行? - shaik moeed
2
@shaikmoeed 你尝试过使用Daphne吗?如果没有的话,我真的建议你去尝试一下:https://github.com/django/daphne - wowkin2
1个回答

12

我找到了答案,runserver 命令可以正确检测到 asgi.py 文件,并且使用 daphne 在 WebSockets 上运行 Django channels 应用程序。不知何故,runsslserver 没有完成相同的工作,它运行的是 wsgi.py 文件而不是 asgi.py 文件。

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

Daphne 是一个官方设计的服务器,用于处理基于 Twisted 模块构建的 django-channels。

因此,最终,我们需要运行两个服务器来分别处理 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

我们应该在测试中使用与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);

我希望这可以节省某人的时间。


命令提示符2中的命令是否使用第一个命令“runsslserver”生成的认证密钥? - Miguel
是的,我们需要为wsgiasgi服务器使用相同的证书。 - shaik moeed

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接