我正在尝试使用Django频道与浏览器建立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();
settings.py
CHANNEL_LAYERS = {
"default": {
"BACKEND": "asgiref.inmemory.ChannelLayer",
"ROUTING": "django_chat_server.routing.channel_routing",
}
}
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。没有用。
答案 0 :(得分:4)
您还应该拥有websocket.connect的使用者并接受连接,只有在接受连接后协议服务器才能完成websocket握手
channel_routing = {
"websocket.connect": consumers.ws_connect,
}
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