推薦使用python3.6以上版本來運行websockets
pip3 install websockets
主要用到的API有:
websockets.connect()
websockets.send()
websockets.recv()
server.py
,用於搭建webscocket服務器,在本地8765端口啟動,接收到消息后會在原消息前加上I got your message:
再返回去。
import asyncio
import websockets
async def echo(websocket, path):
async for message in websocket:
message = "I got your message: {}".format(message)
await websocket.send(message)
asyncio.get_event_loop().run_until_complete(websockets.serve(echo, 'localhost', 8765))
asyncio.get_event_loop().run_forever()
client.py
#!/usr/bin/env python
import asyncio
import websockets
async def hello(uri):
async with websockets.connect(uri) as websocket:
await websocket.send("hello world")
print("< HELLO WORLD")
while True:
recv_text = await websocket.recv()
print("> {}".format(recv_text))
asyncio.get_event_loop().run_until_complete(hello('ws://localhost:8765'))
先執行server.py
,然后執行client.py
,client.py
的輸出結果如下:
< Hello world!
> I got your message: Hello world!
> 2021-03-03 15:11:50
客戶端發送了第一條消息給服務端,服務端接收到后發送了第二條消息,最后一條消息是由服務端主動發送給客戶端的。