Because we have been sending text messages (http) for a long time, we hope to have a phone call (websocket); with the phone, we can enjoy traffic (duplex communication), so we talk word by word (network packet by packet); in order It allows the other party to clearly understand what we mean, so what we say is full of yin and yang, with a slight pause (the length of the package), so that the other party can get our point.
First install websocket dependencies:
pip install websockets
websocket server:
#!/usr/bin/env python
import asyncio
import websockets
async def echo(websocket):
while True:
name = await websocket.recv()
print(f"接收到消息:{name}")
replay = f"Hello {name}"
await websocket.send(replay)
print(f"发送消息结束")
async def main():
async with websockets.serve(echo, "localhost", 8765):
print("服务端启动成功:ws://localhost:8765")
await asyncio.Future() # run forever
asyncio.run(main())
websocket client:
#!/usr/bin/env python
import asyncio
import time
import websockets
async def hello():
async with websockets.connect("ws://localhost:8765") as websocket:
while True:
await websocket.send("Hello world!")
message = await websocket.recv()
print(f"Received: {message}")
time.sleep(1)
asyncio.get_event_loop().run_until_complete(hello())
Run the server first, then the client:
Then start the client:
Or you can use postman to connect: