python websocket用法

合集下载
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

python websocket用法
在Python中,你可以使用第三方库来实现WebSocket通信。

一个常用的WebSocket库是`websockets`。

以下是使用`websockets`库的简单示例:
首先,你需要安装`websockets`库,可以通过以下命令来安装:
```bash
pip install websockets
```
接下来,你可以使用以下代码创建一个简单的WebSocket服务器和客户端:
WebSocket服务器示例:
```python
import asyncio
import websockets
async def handle_client(websocket, path):
# 当有新的连接建立时,这个函数将会被调用
print(f"Client connected: {websocket.remote_address}")
try:
# 接收消息并处理
async for message in websocket:
print(f"Received message: {message}")
# 发送消息回客户端
response = f"Server received: {message}"
await websocket.send(response)
except websockets.exceptions.ConnectionClosedError:
# 连接关闭时的处理
print(f"Client disconnected: {websocket.remote_address}")
# 启动WebSocket服务器
start_server = websockets.serve(handle_client, "localhost", 8765)
# 运行事件循环
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
```
WebSocket客户端示例:
```python
import asyncio
import websockets
async def connect_to_server():
uri = "ws://localhost:8765"
async with websockets.connect(uri) as websocket:
# 发送消息给服务器
message = "Hello, Server!"
await websocket.send(message)
print(f"Sent message: {message}")
# 接收服务器的响应
response = await websocket.recv()
print(f"Received response: {response}")
# 运行事件循环连接到服务器
asyncio.get_event_loop().run_until_complete(connect_to_server())
```
在这个例子中,服务器和客户端都使用`websockets`库,服务器监听在`localhost:8765`,客户端连接到这个地址。

当客户端发送消息时,服务器接收并回复相同的消息。

请注意,WebSocket是一种全双工通信协议,服务器和客户端都可以发送和接收消息。

你可以根据实际需求在上述示例的基础上进行扩展和修改。

相关文档
最新文档