如何为客户端设置子协议列表(Twisted)

How to set subprotocol list for Client (Twisted)

大家好,

我已经创建了一个客户端和一个服务器来通过 websockets 进行通信。 Twisted 库用于 websockets,最终我将把 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))

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

谢谢,

布莱恩

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

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

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", ...}