websockets 是一个专注于正确性、简洁性、健壮性和性能的Python库,用于构建WebSocket服务器和客户端。

它支持多种网络I/O和控制流范式:

  1. 默认实现基于asyncio,即Python的标准异步I/O框架。它提供了一种优雅的基于协程的API。特别适用于同时处理多个客户端的服务器。
  2. threading实现是客户端的一个很好的选择,特别是对于不熟悉asyncio的用户来说。它也可以用于不需要为大量客户端提供服务的服务器。
  3. Sans-I/O实现是为了与第三方库集成而设计的,通常用于应用程序服务器,并且还在websockets内部使用。

下面是一个使用asyncio API的回显服务器示例:

#!/usr/bin/env python

import asyncio
from websockets.server import serve

async def echo(websocket):
    async for message in websocket:
        await websocket.send(message)

async def main():
    async with serve(echo, "localhost", 8765):
        await asyncio.Future()  # run forever

asyncio.run(main())

下面是一个使用threading API发送和接收消息的客户端示例:

#!/usr/bin/env python

import asyncio
from websockets.sync.client import connect

def hello():
    with connect("ws://localhost:8765") as websocket:
        websocket.send("Hello world!")
        message = websocket.recv()
        print(f"Received: {message}")

hello()

不必担心握手、ping和pong等细节,WebSocket规范中的其他行为,websockets会在幕后自动处理,这样你就可以专注于你的应用程序!

此外,websockets还提供了一个交互式客户端:

python -m websockets ws://localhost:8765/
Connected to ws://localhost:8765/.
> Hello world!
< Hello world!
Connection closed: 1000 (OK).


 

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐