【问题标题】:How to set subprotocol list for Client (Twisted)如何为客户端设置子协议列表(Twisted)
【发布时间】:2017-12-06 21:42:18
【问题描述】:

大家好,

我创建了一个客户端和一个服务器来通过 websocket 进行通信。 Twisted 库用于 websocket,最终我会将 GraphQL 字符串从客户端发送到服务器。

但是,我收到一条错误消息:

failing WebSocket opening handshake ('subprotocol selected by server (graphql-ws) not in subprotocol list requested by client ([])')

这是我创建的示例代码:

server.py

class MyServerProtocol(WebSocketServerProtocol):

  def onConnect(self, request):
    custom_header = {}
    if request.headers['sec-websocket-key']:
      custom_header['sec-websocket-protocol'] = 'graphql-ws'
    return (None, custom_header)

  def onOpen(self):
    print "Websocket connection open"

  def onMessage(self, payload, isBinary):
    # Handle GraphQL query string here
    try:
      parsed_message = json.loads(payload)
    except Exception as exp:
      logger.error('Could not parse websocket payload', exc_info=True)
      self.sendClose()
      return 1

  def onClose(self, wasClean, code, reason):
    print("WebSocket connection closed: {0}".format(reason))

client.py

class MyClientProtocol(WebSocketClientProtocol):

  def onConnect(self, response):
    response.protocol = 'graphql-ws'

  def onOpen(self):
    print "Websocket connection open"

  def onMessage(self, payload, isBinary):
    if isBinary:
        print("Binary message received: {0} bytes".format(len(payload)))
    else:
        print("Text message received: {0}".format(payload.decode('utf8')))

  def onClose(self, wasClean, code, reason):
    print("WebSocket connection closed: {0}".format(reason))

有谁知道如何在客户端设置子协议列表?任何帮助将不胜感激。

谢谢,

布赖恩

【问题讨论】:

    标签: python websocket twisted twisted.web twisted.internet


    【解决方案1】:

    创建工厂后,您可以附加自定义子协议:

    factory = WebSocketClientFactory("wss://SERVER_URL")
    factory.protocol = MyClientProtocol
    
    # append custom protocols here:
    factory.protocols.append("graphql-ws")
    
    connectWS(factory)
    

    小心使用“s”(协议 协议)。您可以在“onConnect”方法的响应中检查该协议是否已被服务器接受:

    def OnConnect(self, response):
         print(response)
    
    output: {"peer" : "...", "headers" : { ... }, "protocol": "graphql-ws", ...}
    

    【讨论】:

      【解决方案2】:

      new WebSocket( Url , Protocol[]) 第二个参数是可选的。检查协议参数中允许的字符。第二个是 string 或 string[] 。我不确定你是否要求这样做。

      【讨论】:

      • 这个答案与问题完全无关。
      • 对不起。我现在看到了。我想把它贴在不同的堆栈中
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多