使用Django Channels的Websocket [英] Websocket using Django Channels

查看:305
本文介绍了使用Django Channels的Websocket的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Django渠道与浏览器建立Websocket连接。 websocket无法与服务器连接:

I am trying to use Django channels to establish a websocket connection with the browser. The websocket fails to connect with the server:

[2017/01/23 23:51:50] HTTP GET / 200 [0.03, 127.0.0.1:60445]
[2017/01/23 23:51:51] WebSocket HANDSHAKING /chat/ [127.0.0.1:60451]
[2017/01/23 23:51:56] WebSocket DISCONNECT /chat/ [127.0.0.1:60451]

用于websocket的Javascript:

Javascript used for websocket:

    socket = new WebSocket("ws://" + window.location.host + "/chat/");
    socket.onmessage = function (e) {
        alert(e.data);
    };
    socket.onopen = function () {
        socket.send("hello world");
    };
    // Call onopen directly if socket is already open
    if (socket.readyState == WebSocket.OPEN) socket.onopen();

settings.py

settings.py

CHANNEL_LAYERS = {
    "default": {
        "BACKEND": "asgiref.inmemory.ChannelLayer",
        "ROUTING": "django_chat_server.routing.channel_routing",
    }
}

Routing.py

Routing.py

channel_routing = {
    # Wire up websocket channels to our consumers:
    'websocket.connect': ws_add,
    'websocket.receive': ws_message,
    'websocket.disconnect': ws_disconnect,
}

在加载页面时, ws_add 启动,但最终连接断开。关于如何调试此问题或可能存在问题的任何线索。

On loading the page, ws_add fires up but the connection eventually get's disconnected. Any lead on how can I debug this, or what the problem could be.

我正在使用命令 python manage.py runserver 运行服务器。

I am running the server using the command python manage.py runserver.

编辑:
降级为 twisted 版本16.2.0。没用。

Downgraded to twisted version 16.2.0. No avail.

推荐答案

您还应该为websocket.connect拥有一个使用者,并接受连接,只有在接受连接后,协议服务器将完成websocket握手

You should also have a consumer for the websocket.connect and accept the connection, only after accepting the connection the protocol server will complete the websocket handshake

channel_routing = {
    "websocket.connect": consumers.ws_connect,
}

consumers.py

consumers.py

def ws_connect(message):
    message.reply_channel.send({
        'accept': True
})

请参见 http://channels.readthedocs.io/en/latest/releases/1.0.0.html#websocket-accept-reject-flow

这篇关于使用Django Channels的Websocket的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆