赞
踩
asyncio
库,阅读阅读即可理解websockets
库,还有很多要学习的地方,后面我将为此再开一个自学专栏import asyncio import time import websockets # 处理websocket连接请求的协程函数 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(): # 通过websockets库创建服务器,并指定协议、IP地址和端口号 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())
import asyncio import time import websockets async def start_c(): # 与WebSocket服务器建立连接 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())
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。