Issue
I'm trying to display image that I receive from a test local server inside pyqt window. I tried this link but I couldn't get it work. Could you help with that? Thanks in advance.
Displaying Image (in bytes) in PyQt
Client Code
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_())
Server Code
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)
Solution
There are different problems in this code.
First is that the reading loop is wrong. TCP is a stream protocol. That means that the data may come in a variable number of packets that you must concatenate. So it should be:
image_binaries = b""
while True:
chunk = s.recv(100000000)
if not chunk:
break
image_binaries += chunk
s.close()
Then you have a possible race condition server side. client.send(data)
will return as soon as all the data has been queued for transmission. If another connection immediately occurs, client
will be reused which could cause the previous connection do be closed before everything has been sent. You should use a graceful shutdown here:
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
Answered By - Serge Ballesta
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.