写一个websocket长链接的代码
时间: 2024-05-09 12:17:29 浏览: 20
好的,我可以帮您提供一个简单的Python Websocket长链接代码示例,您可以根据实际需求进行修改:
```python
import asyncio
import websockets
async def websocket_handler(websocket, path):
while True:
# 接收客户端发送的消息
message = await websocket.recv()
print("Received message from client:", message)
# 发送消息给客户端
response = "Server received your message: {}".format(message)
await websocket.send(response)
print("Sent message to client:", response)
async def start_websocket_server(ip, port):
async with websockets.serve(websocket_handler, ip, port):
print("Websocket server started at ws://{}:{}".format(ip, port))
await asyncio.Future() # 防止进程退出
if __name__ == "__main__":
asyncio.run(start_websocket_server("localhost", 5555))
```
此处代码用到了异步IO库 `asyncio` 和Websockets库 `websockets` ,在 `websocket_handler` 函数中处理客户端与服务端间的通信,每当接收到客户端发送来的消息时,服务端会返回一个响应,表示接收到了客户端的消息。客户端可按照websocket协议与此处的服务端进行连接和通信。