gpt4 book ai didi

django - 使用 Django channel 的 Websocket

转载 作者:行者123 更新时间:2023-12-03 23:19:15 31 4
gpt4 key购买 nike

我正在尝试使用 Django channel 与浏览器建立 websocket 连接。 websocket 连接服务器失败:

[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:
    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();

设置.py
CHANNEL_LAYERS = {
"default": {
"BACKEND": "asgiref.inmemory.ChannelLayer",
"ROUTING": "django_chat_server.routing.channel_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启动,但连接最终断开。关于如何调试这个或问题可能是什么的任何线索。

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

编辑:
降级为 twisted版本 16.2.0。徒劳无功。

最佳答案

您还应该有一个 websocket.connect 的消费者并接受连接,只有在接受连接后,协议(protocol)服务器才会完成 websocket 握手

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

消费者.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 - 使用 Django channel 的 Websocket,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41817871/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com