如何编写一个简单的python websockets客户端

时间:2019-10-29 01:46:08

标签: python websocket

如何编写一个简单的Python3 websockets客户端?

鉴于https://github.com/Pithikos/python-websocket-server(一种多客户端服务器实现)已经通过作者提供的Web客户端(即javascript)进行了测试,我想使用标准的python websockets模块编写一个简单的python3客户端。我希望客户端发送一条短信并得到答复(有点像回显服务器)。客户端上没有花哨的东西,没有并发,只需连接,发送,接收和关闭(或退出)即可。

#!/usr/bin/python3

import sys
import websockets

req = 'joe'
if sys.argv[1:]:
    req = sys.argv[1]

with websockets.connect("ws://localhost:9001") as ws:
    print("req: %s" % (req) )
    ws.send(req)
    res = ws.recv()
    print("res: %s" % (res) )

当我运行它时...

medi@medi:~/proto/python/d4> ./client 'hello Joe'
Traceback (most recent call last):
  File "./client", line 10, in <module>
    with websockets.connect("ws://localhost:9001") as ws:
AttributeError: __enter__

我期望能够发送()和recv()。我很难找到基于python的代码(已经看过很多JS客户端)示例。

0 个答案:

没有答案