- 本代码在上一个实战的基础上添加上了线程技能,开辟了一个线程,在线程中运行协程任务
- 实现了简单的websocket的通信
- 代码并不难,注释很详细,直接阅读即可
server端
- server 会接收client发来的消息,并微微修改,我这里是末尾添加感叹号,然后发回给client
import asyncio
import threading
import time
import websockets
async def handler(websocket, path):
print(f"[{time.asctime()} connected!]")
async for message in websocket:
print(f"[{time.asctime()} from client]: " + message)
await websocket.send(message + "!")
async def server_my():
async with websockets.serve(handler, "127.0.0.1", 8765, ping_interval=200, ping_timeout=200,
timeout=2000):
print(f"[{time.asctime()} Server on]")
await asyncio.Future()
def loop_in_thread(new_loop):
asyncio.set_event_loop(new_loop)
new_loop.create_task(server_my())
new_loop.run_forever()
def start():
new_loop = asyncio.new_event_loop()
t = threading.Thread(target=loop_in_thread, kwargs={"new_loop": new_loop})
t.start()
asyncio.run_coroutine_threadsafe(server_my(), new_loop)
if __name__ == '__main__':
start()
client 端
- client 我采用了两个协程任务,分别来处理发送和接收两个功能
import asyncio
import websockets
async def send(websocket):
while True:
message = input("请输入要发送的消息:")
await websocket.send(message)
await asyncio.sleep(1)
async def receive(websocket):
async for response in websocket:
print(f"收到服务器端返回的消息:{response}")
async def main():
async with websockets.connect("ws://localhost:8765") as websocket:
await asyncio.gather(send(websocket), receive(websocket))
if __name__ == '__main__':
asyncio.run(main())