django - 设置 Django channel

标签 django django-channels

我一直在尝试将 Django channel 集成到我现有的 Django 应用程序中。

这是我的 routing.py:

from channels.routing import route

channel_routing = [
    route('websocket.receive', 'chat.consumers.ws_echo', path=r'^/chat/$'),
]

这是我的 consumers.py:

def ws_echo(message):
    message.reply_channel.send({
        'text': message.content['text'],
    })

我正在尝试通过这样做来创建一个套接字:

ws = new WebSocket('ws://' +  window.location.host + '/chat/');

ws.onmessage = function(message) {
  alert(message.data);
};

ws.onopen = function() {
  ws.send('Hello, world');
};

当我运行这段代码时,我的控制台出现以下错误:

WebSocket connection to 'ws://localhost:8000/chat/' failed: Error during WebSocket handshake: Unexpected response code: 404

在我的服务器上,我收到以下错误:

HTTP GET /chat/ 404

根据错误,我认为 Django 给出的是 http 连接而不是 ws 连接。

非常感谢对此问题的任何帮助。

最佳答案

我的设置问题出在我的 nginx 配置上。我所要做的就是添加转发线路,它解决了问题。

location /chat { # Django Channels
            proxy_pass http://0.0.0.0:8001;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "upgrade";

        }

关于django - 设置 Django channel ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48909357/

相关文章:

python - 如何链接Django中保存在不同位置的两个对象

python - django channels 仅在尝试使用 User_login 时出现连接错误

python - BeautifulSoup 和转换 HTML 实体的奇怪行为

html - 为什么在 django 中使用 xhtml2pdf 呈现为 pdf 时,html 表中的某些列会崩溃?

python - 有没有办法让 Graphite 烯与 django GenericRelation 字段一起工作?

Django 模板 : Get current URL in another language

python - Django 中的外部 API 调用缓存

python - Django channel : Alternative of Redis for windows machine?

python - Django channel + 在发布请求后发送 websocket 消息

python - 如何在 Django channel 中为消费者编写单元测试?