websocket-client(websocket)和websockets区别

一、websocket-client 是一个websocket服务的client端模块
导入时需要使用 import websocket 是比较简单易用的模块,典型的用法如下:

import websocket
try:
    import thread
except ImportError:
    import _thread as thread
import time

def on_message(ws, message):
    print(message)

def on_error(ws, error):
    print(error)

def on_close(ws):
    print("### closed ###")

def on_open(ws):
    def run(*args):
        for i in range(3):
            time.sleep(1)
            ws.send("Hello %d" % i)
        time.sleep(1)
        ws.close()
        print("thread terminating...")
    thread.start_new_thread(run, ())


if __name__ == "__main__":
    websocket.enableTrace(True)
    ws = websocket.WebSocketApp("ws://echo.websocket.org/",
                              on_message = on_message,
                              on_error = on_error,
                              on_close = on_close)
    ws.on_open = on_open
    ws.run_forever()

上面是把所有的内置函数引用的一种方法, ws.run_forever()方法放入协程。 如果使用单一发送接受使用如下:

from websocket import create_connection
ws = create_connection("ws://echo.websocket.org/")
print("Sending 'Hello, World'...")
ws.send("Hello, World")
print("Sent")
print("Receiving...")
result =  ws.recv()
print("Received '%s'" % result)
ws.close()

二、websockets是一个模块有server端和client端
基本例子:
这是一个WebSocket服务器示例。 它从客户端读取名称,发送问候语,然后关闭连接。

import asyncio
import websockets

async def hello(websocket, path):
   name = await websocket.recv()
   print(f"< {name}")

   greeting = f"Hello {name}!"

   await websocket.send(greeting)
   print(f"> {greeting}")

start_server = websockets.serve(hello, "localhost", 8765)

asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()

明显看出这里面既有协程也有异歩,所以应该使用python>3.6

在服务器端, 对每个WebSocket连接websockets执行hello一次处理程序协程。处理程序协程返回时,它将关闭连接。

这是一个相应的WebSocket客户端示例。

import asyncio
import websockets

async def hello():
    uri = "ws://localhost:8765"
    async with websockets.connect(uri) as websocket:
        name = input("What's your name? ")

        await websocket.send(name)
        print(f"> {name}")

        greeting = await websocket.recv()
        print(f"< {greeting}")

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

使用connect()作为异步上下文管理器确保了连接正在退出之前关闭hello协程。

查看了websockets的API,发现websockets对协议部分定义的还是很好,方法部分给的还是太少,适于高手使用的工具,对异歩协程和协议不是很清楚的工程师,不建议使用, 就是还达不到开箱即用的程度,websocket-client可以开箱即用而且只有一个客户端,非常好理解。

websocket-client是同步功能的,如果确实想用异歩的websocket建议可以使用autobahn的WebSocket部分,地址:https://autobahn.readthedocs.io/en/latest/websocket/examples.html

  • 1
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值