OPTY

局域网socket投屏

Python简单局域网socket投屏


服务器:

from socket import socket
from threading import Thread
from zlib import compress
from mss import mss


# 截图大小
WIDTH = int(960)
HEIGHT = int(600)


def send_screenshot(conn):
    with mss() as sct:
        rect = {'top': 0, 'left': 0, 'width': WIDTH, 'height': HEIGHT}
        while 'recording':
            img = sct.grab(rect)
            # 压缩等级 (0-9)
            # 并不一定是压缩level越高越好,这里要综合考虑压缩占用时间和网络传输时间
            pixels = compress(img.bgra, 5)
            # 压缩对比
            # level:0 size:4196683
            # level:1 size:248329
            # level:2 size:246512
            # level:9 size:196212
            size = len(pixels)
            size_len = (size.bit_length() + 7) // 8
            conn.send(bytes([size_len]))
            size_bytes = size.to_bytes(size_len, 'big')
            conn.send(size_bytes)
            conn.sendall(pixels)


def main(host='0.0.0.0', port=666):
    sock = socket()
    sock.bind((host, port))
    try:
        sock.listen(5)
        print('Server started.')
        while 'connected':
            conn, addr = sock.accept()
            print('Client connected IP:', addr)
            thread = Thread(target=send_screenshot, args=(conn,))
            thread.start()
    finally:
        sock.close()


if __name__ == '__main__':
    main()

 

客户端

from socket import socket
from zlib import decompress
import cv2
import numpy
from PIL import Image

# 截图大小
WIDTH = int(960)
HEIGHT = int(600)


def recvall(conn, length):
    buf = b''
    while len(buf) < length:
        data = conn.recv(length - len(buf))
        if not data:
            return data
        buf += data
    return buf


# host为server的ip
def main(host='127.0.0.1', port=666):
    watching = True

    sock = socket()
    sock.connect((host, port))
    try:
        while watching:
            size_len = int.from_bytes(sock.recv(1), byteorder='big')
            size = int.from_bytes(sock.recv(size_len), byteorder='big')
            # 解压缩
            bgra = decompress(recvall(sock, size))
            img = Image.frombytes("RGB", (WIDTH, HEIGHT), bgra, "raw", "BGRX")
            np_ar = numpy.array(img, dtype=numpy.uint8)
            # 因为OpenCV模式色彩默认是BGR(红色和蓝色互换了)
            # 这里就是把BGR改成RGB
            np_ar = numpy.flip(np_ar[:, :, :3], 2)
            cv2.imshow("OpenCV show", np_ar)

            if cv2.waitKey(25) & 0xFF == ord("q"):
                cv2.destroyAllWindows()
                break
    finally:
        sock.close()


if __name__ == '__main__':
    main()