Python学习-套接字方式网口传输图片

1. 服务端


 #--------------------------------------------------------------------------------------------------#
# 网口发送接收数据的类
class Send_Rev_Imgs_Netport():

    def __init__(self) -> None:
        pass

    def send_imgs_2_netport(self, img_path, ip, ip_port):
        # 创建socket对象
        client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        try:
            client_socket.connect((ip, int(ip_port)))  # 连接到目标IP地址和端口
            
            # 发送文件名的长度
            file_name_size = len(os.path.basename(img_path))
            client_socket.send(struct.pack('<Q', file_name_size))  # 使用小端序发送文件大小

            # 发送文件名
            filename_bytes = os.path.basename(img_path).encode('utf-8')
            client_socket.send(filename_bytes)
            
            # 发送文件大小
            # send_data = b''
            with open(img_path, 'rb') as f:

                # 发送文件数据
                while True:
                    chunk = f.read(1024)
                    if not chunk:
                        break
                    # send_data+=chunk
                    client_socket.send(chunk)
                # print(send_data)
            print("文件发送完成。")
            return True
        
        except Exception as e:
            print(f"发送过程中发生错误: {e}")
            return False
        
        finally:
            client_socket.close()


        # 网口接收图片
 
        # 套接字方式通过网口接收图片模板
    def receive_image_from_networkport(self, save_img_path, ip, ip_port):
        """
        套接字方式通过网口接收图片模板
        返回保存在下位机的模板的路径,以便后续调用
        """
        # 创建socket对象
        server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        # server_socket.settimeout(3)  # 设置超时时间
        
        # try:

        server_socket.bind((ip, int(ip_port)))  # 绑定到指定IP和端口
        server_socket.listen(1)  # 最多可以挂起5个未完成的连接
        print("等待连接...")
        
        # 接受连接
        client_socket, addr = server_socket.accept()
        print("连接地址: %s" % str(addr))
        
        # 接收文件名长度
        # 接收文件大小
        file_name_size = client_socket.recv(8)
        filesize = struct.unpack('<Q', file_name_size)[0]  # 解包文件大小
        print(filesize)

        # 接收文件名
        filename_bytes = client_socket.recv(filesize)
        print(filename_bytes)
        img_name = filename_bytes.decode('utf-8')
        
        if not img_name:
            raise ValueError("无效的文件名")
        # received_byte = b''
        # 接收文件数据
        with open(save_img_path, 'wb') as f:
            while True:
                chunk = client_socket.recv(1024)
                if not chunk:
                    break
                f.write(chunk)
                # received_byte+=chunk
        
        # print(received_byte)
        print("模板图片接收成功!")
        return addr
        
        # except socket.timeout:
        #     print("连接超时,等待了3秒未连接。")
        #     return None
        
        # except Exception as e:
        #     print(f"接收过程中发生错误: {e}")
        #     return None
        
        # finally:
        #     if 'client_socket' in locals():
        #         client_socket.close()
        #     server_socket.close()

#--------------------------------------------------------------------------------------------------#

2. 客户端

#############################################netport_start#####################################################
# 网口发送接收数据的类
class Send_Rev_Imgs_Netport():
    def __init__(self):
        pass

    def send_imgs_2_netport(self, img_path, ip, ip_port):
        # 创建socket对象
        client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        try:
            client_socket.connect((ip, int(ip_port)))  # 连接到目标IP地址和端口
            
            # 发送文件名的长度
            file_name_size = len(os.path.basename(img_path))
            client_socket.send(struct.pack('<Q', file_name_size))  # 使用小端序发送文件大小

            # 发送文件名
            filename_bytes = os.path.basename(img_path).encode('utf-8')
            client_socket.send(filename_bytes)
            
            # 发送文件大小
            with open(img_path, 'rb') as f:

                # 发送文件数据
                while True:
                    chunk = f.read(1024)
                    if not chunk:
                        break
                    client_socket.send(chunk)
            
            print("文件发送完成。")
            return True
        
        except Exception as e:
            print(f"发送过程中发生错误: {e}")
            return False
        
        finally:
            client_socket.close()

    # 套接字方式通过网口接收图片模板
    def receive_image_from_networkport(self, ip, ip_port):
        """
        套接字方式通过网口接收图片模板
        返回保存在下位机的模板的路径,以便后续调用
        """
        # 创建socket对象
        server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        server_socket.settimeout(5)  # 设置超时时间
        
        try:
            server_socket.bind((ip, int(ip_port)))  # 绑定到指定IP和端口
            server_socket.listen(5)  # 最多可以挂起5个未完成的连接
            print("等待连接...")
            
            # 接受连接
            client_socket, addr = server_socket.accept()
            print("连接地址: %s" % str(addr))
            
            # 接收文件名长度
            # 接收文件大小
            file_name_size = client_socket.recv(8)
            filesize = struct.unpack('<Q', file_name_size)[0]  # 解包文件大小


            # 接收文件名
            filename_bytes = client_socket.recv(filesize)
            img_name = filename_bytes.decode('utf-8')
            
            if not img_name:
                raise ValueError("无效的文件名")
            
            # 确定保存路径
            if "rgb_template" in img_name:
                save_img_dir = os.path.join(os.getcwd(), "temp", "RGB")
            elif "infrared_template" in img_name:
                save_img_dir = os.path.join(os.getcwd(), "temp", "IR")
            else:
                save_img_dir = os.path.join(os.getcwd(), "temp")
            
            if not os.path.exists(save_img_dir):
                os.makedirs(save_img_dir)
            
            save_img_path = os.path.join(save_img_dir, img_name)
            

            # 接收文件数据
            # received_byte = b''
            with open(save_img_path, 'wb') as f:
                while True:
                    chunk = client_socket.recv(1024)
                    if not chunk:
                        break
                    f.write(chunk)
                    # received_byte+=chunk
            # print(received_byte)
            
            print("模板图片接收成功!")
            return save_img_path
        
        except socket.timeout:
            print("连接超时,等待了3秒未连接。")
            return None
        
        except Exception as e:
            print(f"接收过程中发生错误: {e}")
            return None
        
        finally:
            if 'client_socket' in locals():
                client_socket.close()
            server_socket.close()

#############################################netport_end#####################################################

更新:客户端和服务端科一互相发送图片

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

张飞飞飞飞飞

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值