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

时间:2017-12-06 21:42:18

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

大家好,

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

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

谢谢,

布赖恩

2 个答案:

答案 0 :(得分: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", ...}

答案 1 :(得分:-1)

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