我正在尝试在pyqt窗口中显示从测试本地服务器收到的图像。我尝试了此链接,但无法正常工作。你能帮忙吗?提前致谢。
Displaying Image (in bytes) in PyQt
客户代码
import socket
from PIL import Image
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QLabel
from PyQt5.QtGui import QIcon, QPixmap
app = QApplication(sys.argv)
widget = QWidget()
label = QLabel(widget)
HOST = socket.gethostbyname(socket.gethostname())
PORT = 5000
s = socket.socket()
s.connect((HOST, PORT))
while True:
image_binaries = s.recv(100000000)
if not image_binaries:
break
#img = Image.open(BytesIO(image_binaries))
pixmap = QPixmap()
pixmap.loadFromData(image_binaries)
label.setPixmap(pixmap)
widget.resize(pixmap.width(), pixmap.height())
widget.show()
sys.exit(app.exec_())
服务器代码
import socket
HOST = "0.0.0.0"
PORT = 5000
s = socket.socket()
s.bind((HOST, PORT))
data = open(r'Screenshot_1.jpg', 'rb').read()
print("Waiting for connection...")
s.listen(5)
while True:
client, client_address = s.accept()
print(client_address, "is connected")
client.send(data)
答案 0 :(得分:2)
此代码中存在不同的问题。
首先是阅读循环错误。 TCP是流协议。这意味着数据可能会包含一定数量的必须串联的数据包。所以应该是:
image_binaries = b""
while True:
chunk = s.recv(100000000)
if not chunk:
break
image_binaries += chunk
s.close()
然后,您可能会有竞争条件服务器端。所有数据都已排队等待传输后,client.send(data)
将立即返回。如果立即发生另一个连接,client
将被重用,这可能导致之前的连接在发送所有内容之前被关闭。您应在此处使用graceful shutdown:
while True:
client, client_address = s.accept()
print(client_address, "is connected")
client.send(data)
client.shutdown(socket.SHUT_WR) # notify that nothing more is to be sent
_ = client.recv(16) # wait for the client to close when everything has been received
client.close() # Ok, we can explicitely close