赞
踩
websockets官方文档
初步入门可以先看这个大致了解Python3+WebSockets实现WebSocket通信
现在越发觉得学一个东西还是得看官方文档,讲的细,很多一般博客没说明白的地方官方文档都会说明(其实基本95%的博客也都是从官方文档抄代码,阉割一部分内容给你看的,比如我这篇)
#!/usr/bin/env python # WS server example 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()
websockets
每检测到有一个WebSocket连接都会执行一次协程hello
。当协程执行完毕,这个连接也被close关闭了。
#!/usr/bin/env python # WS client example 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())
其实async with在这里的用法和with open(file)挺类似的,这里使用websockets.connect
作为一个异步上下文管理器,来确保协程hello
退出时,websockets的连接也被关闭。这种写法也是官方推荐的在客户端正确关闭一个连接的写法。
recv数据
async def consumer_handler(websocket, path):
async for message in websocket:
await consumer(message)
send数据
async def producer_handler(websocket, path):
while True:
message = await producer()
await websocket.send(message)
recv、send数据
async def handler(websocket, path):
consumer_task = asyncio.ensure_future(
consumer_handler(websocket, path))
producer_task = asyncio.ensure_future(
producer_handler(websocket, path))
done, pending = await asyncio.wait(
[consumer_task, producer_task],
return_when=asyncio.FIRST_COMPLETED,
)
for task in pending:
task.cancel()
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。