Websocket 握手状态 200 异常

Websocket handshake status 200 exception

这是我的客户:

from websocket import create_connection

ws = create_connection("wss://127.0.0.1:8080",
                       sslopt={"cert_reqs": ssl.CERT_NONE, "check_hostname": False, "ssl_version": ssl.PROTOCOL_TLSv1})
        data = json.dumps({"api_command":"sensor_data","session_id":session_id})
        ws.send(data)

这是我的服务器:

if __name__ == '__main__':

    txaio.start_logging(level='debug')

    # SSL server context: load server key and certificate
    # We use this for both WS and Web!
    contextFactory = ssl.DefaultOpenSSLContextFactory('keys/server.key',
                                                      'keys/server.crt')

    factory = WebSocketServerFactory(u"wss://127.0.0.1:9000")
    # by default, allowedOrigins is "*" and will work fine out of the
    # box, but we can do better and be more-explicit about what we
    # allow. We are serving the Web content on 8080, but our WebSocket
    # listener is on 9000 so the Origin sent by the browser will be
    # from port 8080...
    factory.setProtocolOptions(
        allowedOrigins=[
            "https://127.0.0.1:8080",
            "https://localhost:8080",
        ]
    )

    factory.protocol = MyServerProtocol
    listenWS(factory, contextFactory)

    webdir = File(".")
    webdir.contentTypes['.crt'] = 'application/x-x509-ca-cert'
    web = Site(webdir)
    reactor.listenSSL(8080, web, contextFactory)
    #reactor.listenTCP(8080, web)

reactor.run()

当我运行客户端时,在客户端抛出如下错误

websocket._exceptions.WebSocketBadStatusException: Handshake status 200

在服务器上时:

2017-08-23T16:08:58+0300 WebSocketServerFactory (TLS) starting on 9000
2017-08-23T16:08:58+0300 Starting factory <autobahn.twisted.websocket.WebSocketServerFactory object at 0x04AADAF0>
2017-08-23T16:08:58+0300 Site (TLS) starting on 8080
2017-08-23T16:08:58+0300 Starting factory <twisted.web.server.Site object at 0x04ACD770>
2017-08-23T16:09:32+0300 "127.0.0.1" - - [23/Aug/2017:13:09:32 +0000] "GET / HTTP/1.1" 200 2042 "-" "-"

我不明白这是什么问题。我的服务器来自这个例子https://github.com/crossbario/autobahn-python/tree/master/examples/twisted/websocket/echo_tls。如果我使用像该示例中所示的客户端,它连接得很好。但是我无法使用简单的 websocket 库进行连接。

websocket客户端create_connection处抛出异常

而不是

ws = create_connection(
    "wss://127.0.0.1:8080",
    sslopt={"cert_reqs": ssl.CERT_NONE, 
            "check_hostname": False, 
            "ssl_version": ssl.PROTOCOL_TLSv1
    }
)

使用

ws = create_connection(
    "ws://127.0.0.1:8080",
    sslopt={"cert_reqs": ssl.CERT_NONE, 
            "check_hostname": False, 
            "ssl_version": ssl.PROTOCOL_TLSv1}
)

应该是'ws'而不是'wss'。

您可以使用 websocket-server,如果您需要更多帮助,请告诉我