我的任务是使用python套接字编程将一些图像通过网络发送到其他计算机。但是这样做会导致服务器端映像损坏。我不明白为什么我的图像在服务器计算机上接收时会被损坏。以下是我在两台不同的计算机上尝试过的代码。
我尝试了不同的编码技术,例如base64,utf8等,但无法获得预期的结果
import socket
import sys
import traceback
from threading import Thread
import base64
def main():
start_server()
def start_server():
host = "172.16.15.52"
port = 8220 # arbitrary non-privileged port
soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
soc.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # SO_REUSEADDR flag tells the kernel to reuse a local socket in TIME_WAIT state, without waiting for its natural timeout to expire
print("Socket created")
try:
soc.bind((host, port))
except:
print("Bind failed. Error : " + str(sys.exc_info()))
sys.exit()
soc.listen(5) # queue up to 5 requests
print("Socket now listening")
# infinite loop- do not reset for every requests
while True:
connection, address = soc.accept()
ip, port = str(address[0]), str(address[1])
print("Connected with " + ip + ":" + port)
try:
Thread(target=client_thread, args=(connection, ip, port)).start()
except:
print("Thread did not start.")
traceback.print_exc()
soc.close()
def client_thread(connection, ip, port, max_buffer_size = 64000):
is_active = True
while is_active:
client_input = receive_input(connection, max_buffer_size)
if "--quit--" in client_input:
connection.close()
is_active = False
else:
connection.sendall("-".encode("utf8"))
def receive_input(connection, max_buffer_size):
client_input = connection.recv(max_buffer_size)
imageData = client_input
fh = open("result_img/imageToSave.png","wb")
fh.write(imageData.decode('base64'))
fh.close()
client_input_size = sys.getsizeof(client_input)
if client_input_size > max_buffer_size:
print("The input size is greater than expected {}".format(client_input_size))
decoded_input = client_input.decode("utf8").rstrip() # decode and strip end of line
result = process_input(decoded_input)
return result
def process_input(input_str):
return str(input_str)
if __name__ == "__main__":
main()
import socket
import sys
import random
from time import time
import os
import base64
def main():
soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = "172.16.15.52"
port = 8220
try:
soc.connect((host, port))
except:
print("Connection error")
sys.exit()
fileNames = os.listdir('record/result_img/')
for i in fileNames:
with open('record/result_img/'+i, "rb") as imageFile:
str = base64.b64encode(imageFile.read())
if len(str) <= 62000: # size of the image should be less than 64kb due to limitation of TCP packets
message = str
soc.sendall(message)
if soc.recv(64000).decode("utf8") == "-":
pass # null operation
if __name__ == "__main__":
main()
预期结果是应该在服务器端以相似的方式接收客户端的图像