我正在运行我的服务器代码,该服务器代码似乎能够将图片发送到客户端,但是看起来只发送了一个图片文件,一旦手动打开该文件就全黑了。此外,客户端在尝试显示收到的图片时会出错。
我试图将字节转换回图片,这就是给我错误的部分。
import cv2 #SERVER
import time
import socket
import glob
import os
host = "127.0.0.1"
port = 5000
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
s.bind((host,port))
s.listen(5)
print("server started...")
path1 = (r"C:\Users\Desktop\opencvpics")
def readFileImages():
st = os.path.join(path1,"*.png")
print(st)
return glob.glob(st)
list1 = readFileImages()
print(list1,"list1......")
print(type(list1))
while True:
c,addr = s.accept()
print(f"connection from {addr} has been established !")
c.send(bytes("welcome to the server".encode()))
for pics in list1:
f = open(pics,'rb')
l = f.read(1024)
#while (l):
c.send(l)
print('Sent ',repr(l))
#l = f.read(1024)
f.close()
print(pics,"sdfasdfsadadfsafsas")
print(type(f),type(l))
print('Done sending')
c.send('Thank you for connecting'.encode())
import socket #CLIENT
from typing import Optional,Any
import cv2
from PIL import Image
import io
import pickle
host = "127.0.0.1"
port = 5000
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect((host,port))
s.send('Hello server!'.encode())
with open('received_file.png','wb') as f:
print('file is open')
print('receiving data...')
data = s.recv(1024)
print('data=%s',data)
f.write(data)
print('Successfully get the files')
print('connection closed')
print(type(data))
print(len(data))
image = Image.open(io.BytesIO(data))
image.show()
s.close()
这是来自客户端的错误,但是请注意,我必须在此处缩小代码以匹配布局,因此此错误消息中的第35行可能对应于另一行。
Traceback (most recent call last):
File "C:/Users/PycharmProjects/client-server/client.py",line 35,in <module>
image = Image.open(io.BytesIO(data))
File "C:\Users\PycharmProjects\client-server\venv\lib\site-packages\PIL\Image.py",line 2818,in open
raise IOError("cannot identify image file %r" % (filename if filename else fp))
OSError: cannot identify image file <_io.BytesIO object at 0x07D02330>