请编写python实现websocket服务器例子
时间: 2023-06-06 21:07:49 浏览: 181
websocket-python示例
好的,我可以为您提供一个简单的Python WebSocket服务器的示例代码,如下:
```python
import asyncio
import websockets
async def handle_client(websocket, path):
# 新的 WebSocket 连接
print("New client connected.")
try:
# 向客户端发送欢迎消息
await websocket.send("Welcome to the WebSocket server!")
while True:
# 从客户端接收消息
message = await websocket.recv()
print(f"Received message: {message}")
# 处理消息
response = f"You said: {message}"
# 回复客户端消息
await websocket.send(response)
except websockets.exceptions.ConnectionClosed:
# WebSocket 连接已关闭
print("Client connection closed.")
async def main():
async with websockets.serve(handle_client, "localhost", 8000):
print("WebSocket server listening on port 8000...")
await asyncio.Future() # wait forever
if __name__ == '__main__':
asyncio.run(main())
```
您可以在本地运行此WebSocket服务器,它将监听端口8000,并在客户端连接时发送欢迎消息。当它收到客户端的消息时,它将简单地回复相同的消息。此代码使用Python的asyncio和websockets库,因此确保您已经安装了它们。
阅读全文