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?
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"})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With