在Python中编写WebSocket服务端程序,你可以使用`websockets`库。以下是一个简单的示例,展示了如何使用`websockets`库创建一个WebSocket服务器:
```python
import asyncio
import websockets
async def echo(websocket, path):
async for message in websocket:
message = f"I got your message: {message}"
await websocket.send(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端口上运行的WebSocket服务器。当客户端连接到这个服务器并发送消息时,服务器会将接收到的消息原样返回,前面加上"I got your message: "。
如果你需要创建一个WebSocket客户端,可以使用以下代码:
```python
import asyncio
import websockets
async def hello():
uri = "ws://localhost:8765"
async with websockets.connect(uri) as websocket:
await websocket.send("Hello, WebSocket!")
response = await websocket.recv()
print(response)
asyncio.get_event_loop().run_until_complete(hello())
这段代码创建了一个WebSocket客户端,连接到前面创建的服务器,发送一条消息"Hello, WebSocket!",然后接收并打印服务器的响应。
请确保你的Python版本是3.6或更高,因为`websockets`库需要Python 3.6及以上版本才能运行。