- 利用python协程库写了关于websocket通信的简单代码
- 流程比较简单粗略,主要用于学习协程
asyncio
库,阅读阅读即可理解 - 关于
websockets
库,还有很多要学习的地方,后面我将为此再开一个自学专栏
server 端代码
import asyncio
import time
import websockets
async def handler(websocket):
print(f"[{time.asctime()} connection established]")
async for message in websocket:
print(f"[{time.asctime()} from client] {message}")
await websocket.send(message)
async def start_s():
async with websockets.serve(handler, "localhost", 8765, ping_interval=200, ping_timeout=200, timeout=2000):
print(f"{time.asctime()}[Server Started]")
await asyncio.Future()
if __name__ == '__main__':
asyncio.run(start_s())
client 端代码
import asyncio
import time
import websockets
async def start_c():
async with websockets.connect("ws://localhost:8765", ping_interval=200, ping_timeout=200,
timeout=2000) as websocket:
while True:
msg = input("please input: ")
await websocket.send(msg)
message = await websocket.recv()
print(f"[{time.asctime()}from server]: {message}")
if __name__ == '__main__':
asyncio.run(start_c())