python和pyqt5基于tcp 多客户端网络传输的架构,实现本地图片的传输和保存!
时间: 2024-03-17 11:44:54 浏览: 32
以下是一个基于TCP多客户端网络传输的架构,使用Python和PyQt5实现本地图片的传输和保存的代码示例:
服务器端代码:
```python
from PyQt5.QtCore import *
from PyQt5.QtNetwork import *
import sys
def onNewConnection():
client = server.nextPendingConnection()
print("新客户端连接:", client.peerAddress().toString())
client.readyRead.connect(lambda: readData(client))
client.disconnected.connect(lambda: print("客户端断开连接:", client.peerAddress().toString()))
def readData(client):
data = client.readAll()
fileName = "receivedImage.png" # 保存的文件名
file = QFile(fileName)
if file.open(QIODevice.WriteOnly): # 打开文件进行写入
file.write(data)
file.close()
print("文件保存成功:", fileName)
else:
print("文件保存失败:", fileName)
app = QCoreApplication(sys.argv)
server = QTcpServer()
server.listen(QHostAddress.Any, 12345) # 在本地监听端口 12345
if not server.isListening():
print("服务器启动失败")
sys.exit(-1)
print("服务器启动成功")
server.newConnection.connect(onNewConnection)
sys.exit(app.exec_())
```
客户端代码:
```python
from PyQt5.QtCore import *
from PyQt5.QtNetwork import *
import sys
app = QCoreApplication(sys.argv)
socket = QTcpSocket()
socket.connectToHost("127.0.0.1", 12345) # 连接服务器
if not socket.waitForConnected():
print("无法连接到服务器")
sys.exit(-1)
print("已连接到服务器")
fileName = "localImage.png" # 待发送的文件名
file = QFile(fileName)
if not file.open(QIODevice.ReadOnly):
print("文件打开失败:", fileName)
sys.exit(-1)
data = file.readAll()
socket.write(data) # 发送文件
print("文件发送成功:", fileName)
sys.exit(app.exec_())
```
在实际应用中,还需要考虑文件传输过程中的数据安全性和网络连接的稳定性等问题。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![py](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)