在 JavaScript 中,浏览器可以将子协议(protocol)指定为 WebSocket 创建中的第二个参数:
socket=new WebSocket(url, subprotocol)
在 Chrome 中进行实验,这会作为 header 中的 Sec-WebSocket-Protocol
元素正确发送到服务器。
使用Django channel ,一个简单的消费者
def ws_add(message):
message.reply_channel.send({"accept": True,})
给出错误
WebSocket connection to 'xxx' failed: Error during WebSocket handshake: Sent non-empty 'Sec-WebSocket-Protocol' header but no response was received.
在 Django channel 的 ws_add 函数中接受该连接请求的正确方法是什么?
最佳答案
您必须指定要在 websocket.accept
消息中使用的子协议(protocol)。例如,如果您继承 channels.generic.websocket.WebsocketConsumer
(也适用于 SyncConsumer
)并使用 Sec-WebSocket-Protocol
我的协议(protocol)
:
class MyProtocolConsumer(WebsocketConsumer):
def websocket_connect(self, message):
self.base_send({"type": "websocket.accept", "subprotocol": "my-protocol"})
关于python - Django channel 。如何使用子协议(protocol)响应 WebSocket 打开请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42357140/