1. 发送端
import socket
import structdef send_image(filename):# 创建socket对象client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)try:client_socket.connect(('192.168.129.160', 12345)) # 连接到Ubuntu单片机的IP地址和端口# 发送文件名client_socket.send(filename.encode('utf-8'))print(filename.encode('utf-8'))# 发送文件大小with open(filename, 'rb') as f: # 确保文件在这里打开filesize = f.seek(0, 2) # 获取文件大小f.seek(0)client_socket.send(struct.pack('<I', filesize)) # 发送文件大小,使用小端序# 发送文件数据while True:chunk = f.read(1024)if not chunk:breakclient_socket.send(chunk)print("文件发送完成。")except Exception as e:print(f"发送过程中发生错误: {e}")finally:client_socket.close() # 确保socket连接被关闭if __name__ == "__main__":send_image(r'E:\Desktop\Work_Project\API2\fpga\siamfc-pytorch\video\111.png') # 替换为你的图片路径
2. 接收端
# 客户端
import os.path
import socket
import structdef receive_image_from_networkport():"""无输入返回保存在下位机的模板的路径,以便后续调用"""# 保存路径save_img_dir = r"E:\Desktop\Work_Project\API2\fpga\api\temp"if not os.path.exists(save_img_dir):os.makedirs(save_img_dir)# 创建socket对象server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)server_socket.bind(('192.168.129.160', 12345)) # 监听所有网络接口上的12345端口server_socket.listen(1) # 最多可以挂起1个未完成的连接print("等待连接...")# 接受连接client_socket, addr = server_socket.accept()print("连接地址: %s" % str(addr))# 接收文件名和文件大小filename = client_socket.recv(1024).decode('utf-8')import relast_str = filename.split(".")[-1]cleaned_last_str = re.sub(r'[^a-zA-Z]', '', last_str)if cleaned_last_str[-1] == 'r':cleaned_last_str = cleaned_last_str[:-1]filename = filename.split(".")[0] + f".{cleaned_last_str}"img_name = filename.split("\\")[-1]save_img_path = os.path.join(save_img_dir, img_name)print(save_img_path)filesize = int.from_bytes(client_socket.recv(4), byteorder='little')# 接收文件数据with open(save_img_path, 'wb') as f:while True:chunk = client_socket.recv(1024)if not chunk:breakf.write(chunk)print("模板图片上传成功!")client_socket.close()server_socket.close()print("save_img_path", save_img_path)return save_img_pathif __name__ =='__main__':img_path = receive_image_from_networkport()print(img_path)
先运行接收端的代码,且ip改为接收端的ip,然后选择发送图片,运行发送端的代码。