python用socket传输图片

本来想一次连接发送多张图片,但由于处理间隔的逻辑容易导致图片丢失等问题,所以这里采用的是每次连接只发送一张图片

发送的形式是base64编码,可以有效的适用于各种项目

客户端

import time
import cv2
import os
import base64
from socket import *


class Client:
    def __init__(self, host="127.0.0.1", port=8001):
        self.host = host
        self.port = port
        self.socket = self.connect()

    def connect(self):
        tcp_socket = socket()
        tcp_socket.connect((self.host, self.port))
        return tcp_socket
    
    # 发送的是编码,有些项目中就不需要保存路径,直接发送编码了
    def base64_encode_img(self, img_data):
        _, image_encoded = cv2.imencode('.jpg', img_data)
        image_bytes = image_encoded.tobytes()
        image_base64 = base64.b64encode(image_bytes).decode('utf-8')
        return image_base64

    def get_img(self, img_path):
        img = cv2.imread(img_path)
        img_d = self.base64_encode_img(img)
        img_b = img_d.encode()
        return img_b

    def send_msg(self, msg):
        self.socket.send(msg.encode())

    def send_img(self, img_path):
        img_data = self.get_img(img_path)
        n = 0
        while True:
            self.socket.send(img_data[n:n + 1024])
            n += 1024
            if n > len(img_data):
                print(f"已发送:{img_path}")
                break

    def close(self):
        self.socket.close()


if __name__ == '__main__':

    path = "C:/Users/cheng/Desktop/Spider/dilireba"   # 图片路径
    # path = "C:/Users/cheng/Desktop/Spider/gulinazha"
    # path = "C:/Users/cheng/Desktop/Spider/boduo"
    pics = os.listdir(path)
    for pic in pics:
        C = Client(host="127.0.0.1", port=8001)
        p_p = path + "/" + pic
        C.send_img(p_p)  # 发送单张图片
        C.close()

服务端

服务器与连接分离处理,可以有效控制连接,避免单个连接影响服务运行

import os
from socket import *
import base64


# 图片解码
def base64_decode_img(base64_code):
    """
    :param base64_code: base64编码
    :return: 二进制据,直接写入保存为图片
    """
    img_bytes = base64.b64decode(base64_code)
    return img_bytes


class WebSocketServer:
    def __init__(self, host="127.0.0.1", port=8001):
        self.socket = socket()
        self.host = host
        self.port = port

    def bind(self):
        """监听套接字"""
        self.socket.bind((self.host, self.port))
        self.socket.listen()  # 设置监听套接字

    def bind_connection(self):
        """建立连接"""
        while True:
            print("等待连接....")
            conn, addr = self.socket.accept()  # 连接 conn是连接对象;addr=(host,port)
            print(f"连接到:{addr[0]}\t端口:{addr[1]}")
            return conn, addr

    def close(self):
        """ 关闭监听套接字"""
        self.socket.close()


class Connection:
    def __init__(self, conn, addr):
        self.conn = conn
        self.addr = addr
        self.save_path = "recv/"
        self.flag = False

    def close(self):
        """断开连接"""
        self.conn.close()
        print(f"{self.addr[0]}:{self.addr[1]}断开连接")

    def send_msg(self, message):
        """发送信息"""
        self.conn.send(message.encode())

    def receive_msg(self, bufsize=1024):
        """接受信息"""
        data_received = self.conn.recv(bufsize).decode()
        return data_received

    def handle(self, count):
        if not os.path.exists(self.save_path):
            os.makedirs(self.save_path)
        img_data = "" # 需要存储的图片数据
        while True:
            data = self.receive_msg()  # 持续获取该对象信息
            if data:
                img_data += data
            else:
                self.flag = True
                break
        d = base64_decode_img(img_data)
        with open(f"{self.save_path}/{count}.jpg", "wb") as f:
            f.write(d) if d else None


if __name__ == '__main__':
    webserver = WebSocketServer(host="127.0.0.1", port=8001)
    webserver.bind()
    count = 0
    while True:
        conn, addr = webserver.bind_connection()
        con = Connection(conn, addr)
        while True:
            con.handle(count)
            count += 1
            print(f"完成{count}")
            if con.flag: break

你可能感兴趣的:(python,开发语言,websocket)