问题
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]
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
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,
}
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.
I am running the server using the command python manage.py runserver
.
Edit:
Downgraded to twisted
version 16.2.0. No avail.
回答1:
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
def ws_connect(message):
message.reply_channel.send({
'accept': True
})
see http://channels.readthedocs.io/en/latest/releases/1.0.0.html#websocket-accept-reject-flow
来源:https://stackoverflow.com/questions/41817871/websocket-using-django-channels