django-channels parse json/data sent via sockets

1.1k views Asked by At

I have this javascript code that send data to channels

// Note that the path doesn't matter for routing; any WebSocket
// connection gets bumped over to WebSocket consumers
socket = new WebSocket("ws://" + window.location.host + "/chat/");
socket.onmessage = function(e) {
    alert(e.data);
}
socket.onopen = function() {
    socket.send({"test":"data"});
}
// Call onopen directly if socket is already open
if (socket.readyState == WebSocket.OPEN) socket.onopen();

I'm curios how from message I can get the json {"test":"data"}

here's the view

# Connected to websocket.connect
@channel_session
def ws_connect(message, key):
    # Accept connection
    message.reply_channel.send({"accept": True})
1

There are 1 answers

0
hoefling On

You implemented the connection callback, but did not implement what should happen when a message arrives the server endpoint. Add add message receive function:

def on_receive(message):
    print('test received: {}'.format(message.content['test']))

Register the function in routing.py:

channel_routing = [
    route("websocket.connect", ws_connect),
    route("websocket.receive", on_receive),
]

The JSON message you send will be stored in message.content which is basically just a python dict.