websocket:两台PC间数据传输

项目要求在两台PC间进行图像传输,写了个小小的例子,如下:

服务器端:

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

功能是接收客户端传来的图,并放进recv文件夹下。

客户端:

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 = "/home/tx207/Desktop/img1"   # 图片路径
    # 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="192.168.253.168", port=8001)
        p_p = path + "/" + pic
        C.send_img(p_p)  # 发送单张图片
        C.close()

运行服务器端程序时,出现报错:

Traceback (most recent call last):
  File "server.py", line 79, in 
    webserver.bind()
  File "server.py", line 24, in bind
    self.socket.bind((self.host, self.port))
OSError: [Errno 99] Cannot assign requested address

这种情况说明服务器无法绑定端口IP,一顿搜索后发现了问题所在:

在你的服务器上,这里host后面所跟的,必须是内网IP,而不是公网IP。

但是!在这里写内网IP之后,你在浏览器访问的时候还是用公网IP去进行访问!

如果你不知道你的内网IP的多少,那么,你可以写”0.0.0.0”,它表示你服务器上所有的IP都会被监听。也就是说,你可以这样弄:

webserver = WebSocketServer(host="0.0.0.0", port=8001)

经验证,运行成功!

在这里,要感谢大神!http://t.csdnimg.cn/2iVsw

你可能感兴趣的:(python笔记,websocket,python,网络协议)