Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Channels. How to respond to a WebSocket open request with a subprotocol?

In JavaScript a browser can specify a sub-protocol as the second parameter in a WebSocket creation:

socket=new WebSocket(url, subprotocol)

Experimenting with Chrome, this is correctly sent to the server as a Sec-WebSocket-Protocol element in the header.

Using Django channels, a simple consumer

def ws_add(message):
    message.reply_channel.send({"accept": True,})

gives the error

WebSocket connection to 'xxx' failed: Error during WebSocket handshake: Sent non-empty 'Sec-WebSocket-Protocol' header but no response was received.

What is the correct way to accept that connection request in Django channels' ws_add function?

like image 576
Kim SJ Avatar asked Feb 21 '17 01:02

Kim SJ


1 Answers

You have to specify the subprotocol to use in the websocket.accept message. For example, if you subclass channels.generic.websocket.WebsocketConsumer (also works with SyncConsumer) and using a Sec-WebSocket-Protocol of my-protocol:

class MyProtocolConsumer(WebsocketConsumer):
    def websocket_connect(self, message):
        self.base_send({"type": "websocket.accept", "subprotocol": "my-protocol"})
like image 189
fermayo Avatar answered Sep 23 '22 00:09

fermayo