在现代互联网开发中,WebSocket是一种强大的全双工通信协议,能够实现服务器与客户端之间的实时数据交互。通过结合Python3和`websockets`库,我们可以轻松搭建一个WebSocket服务端或客户端。✨
首先,确保安装了`websockets`库:`pip install websockets`。接着,创建一个简单的WebSocket服务端代码如下:
```python
import asyncio
import websockets
async def echo(websocket, path):
async for message in websocket:
print(f"Received: {message}")
await websocket.send(f"Echo: {message}")
start_server = websockets.serve(echo, "localhost", 8765)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
```
上述代码会监听`localhost:8765`,并实时响应客户端发送的消息。💡
对于客户端部分,同样使用`websockets`库即可轻松连接服务端:
```python
import asyncio
import websockets
async def client():
uri = "ws://localhost:8765"
async with websockets.connect(uri) as websocket:
await websocket.send("Hello Server!")
response = await websocket.recv()
print(response)
asyncio.run(client())
```
运行后,你将看到服务端打印接收到的消息,并回传给客户端。🚀
通过这种方式,你可以快速构建实时应用,如在线聊天室、股票行情推送等。快试试吧!💪
标签:
免责声明:本文由用户上传,如有侵权请联系删除!