Python websocket创建连接

时间:2017-08-25 07:05:11

标签: python ssl websocket autobahn

我有这个服务器

https://github.com/crossbario/autobahn-python/blob/master/examples/twisted/websocket/echo_tls/server.py

我想用这段代码连接到服务器:

ws = create_connection("wss://127.0.0.1:9000")

我需要向create_connection添加哪些选项?添加sslopt={"cert_reqs": ssl.CERT_NONE}不起作用:

websocket._exceptions.WebSocketBadStatusException: Handshake status 400

2 个答案:

答案 0 :(得分:2)

这有效

import asyncio
import websockets
import ssl

async def hello():
    async with websockets.connect('wss://127.0.0.1:9000',ssl=ssl.SSLContext(protocol=ssl.PROTOCOL_TLS)) as websocket:
        data = 'hi'
        await websocket.send(data)
        print("> {}".format(data))

        response = await websocket.recv()
        print("< {}".format(response))

asyncio.get_event_loop().run_until_complete(hello())

答案 1 :(得分:0)

对我来说,问题中的选项似乎有效:

from websocket import create_connection
import ssl

ws = create_connection("wss://echo.websocket.org", sslopt={"cert_reqs": ssl.CERT_NONE})

ws.send("python hello!")
print (ws.recv())
ws.close()

另请参阅此处: https://github.com/websocket-client/websocket-client#faq

注意:我正在将Win7与python 3.6.5一起使用,并安装了以下软件包(pip):

  • simple-websocket-server == 0.4.0
  • websocket-client == 0.53.0
  • websockets == 6.0