在Python中连接WebSocket可以通过多种库实现,以下是使用`websockets`库连接WebSocket的基本步骤:
1. 安装`websockets`库:
```bash
pip install websockets
2. 创建一个WebSocket客户端:
```python
import asyncio
import websockets
async def hello():
uri = "ws://example.com/websocket" 替换为你的WebSocket服务器地址
async with websockets.connect(uri) as websocket:
await websocket.send("Hello, WebSocket!") 发送消息
response = await websocket.recv() 接收消息
print(response)
asyncio.run(hello())
3. 创建一个WebSocket服务器(可选):
```python
import asyncio
import websockets
async def echo(websocket, path):
async for message in websocket:
print(f"Received message: {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()
以上代码展示了如何创建一个简单的WebSocket服务器和客户端。服务器端代码会监听来自客户端的消息,并将接收到的消息回传给客户端。客户端代码则连接到服务器,发送一条消息,并等待接收服务器的响应。
请根据你的具体需求修改上述代码中的URI和服务器地址。