【问题标题】:Python websocket create connectionPython websocket创建连接
【发布时间】:2017-08-25 07:05:11
【问题描述】:

我有这台服务器

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

【问题讨论】:

  • 您是否遇到任何错误?
  • 是的,websocket._exceptions.WebSocketBadStatusException:握手状态 400
  • 您使用的是哪个 websocket 包?如果是websocket,那似乎已经严重过时了。请改用websocketswebsocket-client
  • 我正在使用 websocket-client,在 python 3.6 上使用 pip install websocket-client 安装

标签: python ssl websocket autobahn


【解决方案1】:

这行得通

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())

【讨论】:

  • 这让我在通过代理连接到 websocket 时节省了几天的时间。谢谢。
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-03-11
    • 1970-01-01
    • 2017-11-20
    • 1970-01-01
    • 1970-01-01
    • 2021-10-16
    • 1970-01-01
    • 2017-01-17
    相关资源
    最近更新 更多