python websocket 收和发代码
时间: 2024-11-22 20:29:16 浏览: 15
Python中使用WebSockets进行收发数据通常需要依赖第三方库如`websocket`或`autobahn.twisted`。以下是使用`websocket`库的一个简单示例:
首先,安装所需的库:
```bash
pip install websocket-client
```
然后,发送端(客户端)代码:
```python
import websocket
import json
def on_message(ws, message):
print(f"Received: {message}")
def on_error(ws, error):
print(f"Error: {error}")
def on_close(ws):
print("Connection closed.")
def on_open(ws):
# 发送消息到服务器
data = {"action": "send", "message": "Hello Server!"}
ws.send(json.dumps(data))
if __name__ == "__main__":
url = "ws://your-websocket-server.com"
websocket.enableTrace(True) # 开启调试信息
ws = websocket.WebSocketApp(url,
on_message = on_message,
on_error = on_error,
on_close = on_close)
ws.on_open = on_open
ws.run_forever()
```
接收端(服务端)通常处理WebSocket连接,并监听来自客户端的消息。这取决于你的服务器框架,但基本思路类似,这里是一个简单的示例:
```python
# 这边假设你有一个WebSocketServer实例,用于接受连接并处理请求
class WebSocketServer:
def __init__(self):
self.connections = []
def handle_client(self, client):
for msg in iter(client.recv, b''):
data = json.loads(msg)
if data["action"] == "send":
print(f"Received from client: {data['message']}")
client.close()
def start_listening(self, host, port):
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((host, port))
server.listen()
while True:
conn, addr = server.accept()
self.connections.append(conn)
thread = threading.Thread(target=self.handle_client, args=(conn,))
thread.start()
```
阅读全文