Python 屏幕广播

'''
server.py
'''
from socket import socket
from threading import Thread
from zlib import compress
from mss import mss
 
# 截图大小
WIDTH = int(1366 / 1)
HEIGHT = int(768 / 1)
 
 
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, 1)
            # 压缩对比
            # 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=5000):
    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()


'''
client.py
'''
from socket import socket
from zlib import decompress
import cv2
import numpy
from PIL import Image
 
# 截图大小
WIDTH = int(1366 / 1)
HEIGHT = int(768 / 1)
 
 
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='10.100.40.52', port=5000):
    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()

 

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值