服务端
import socket
import threading
import time
import sys
import zlib
import numpy as np
from PIL import ImageGrab
server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
connects = []
server.bind(('', 9090))
def send(message,address,server):
length = sys.getsizeof(message)
time.sleep(.01)
server.sendto(b"start", address)
print(length)
for i in range(0,int(length/(60*1024))):
# time.sleep(.02)
server.sendto(message[i*60*1024:(i+1)*60*1024], address)
time.sleep(.02)
server.sendto(message[len(message)-(len(message)%(60*1024)):], address)
server.sendto(b"end", address)
time.sleep(.01)
def ScreenShare():
while True:
screen = np.array(ImageGrab.grab(bbox=(0, 0, 1920, 1080)))
message = screen.tobytes()
message = zlib.compress(message)
for _ in connects:
try:
send(message, _, server)
except:
connects.remove(_)
# send(message, addr, server)
thread = threading.Thread(target=ScreenShare, args=())
thread.start()
while True:
print(connects)
back_msg, addr = server.recvfrom(1024)
if addr not in connects:
connects.append(addr)
print(back_msg.decode("utf-8"), addr, len(connects))
客户端
import random
import socket
import sys
import threading
import zlib
import cv2
import numpy as np
from numpy import uint8
message_pool = []
client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
client.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
client.sendto("我是设备1号".encode('utf-8'), ('', 9090))
# cv2.namedWindow("window", 0)
message = b""
key = False
def cyberpunk():
r = random.randint(0,100)
if r>96:
return (1920,1080,3)
elif r>86:
return (1080,3,1920)
elif r>76:
return (1920,1080,3)
elif r>70:
return (1920,3240,1)
else:
return (1080,1920,3)
def ScreenShow():
cv2.namedWindow("window", 0)
while True:
if len(message_pool)!=0:
try:
# cv2.namedWindow("window", 0)
print(sys.getsizeof(message_pool[0]))
message = zlib.decompress(message_pool[0])
y = np.frombuffer(message, dtype=uint8)
y.shape = (1080, 1920, 3)
# y.shape = (1920,1080,3)
# y.shape = cyberpunk()
imm = cv2.cvtColor(y, cv2.COLOR_RGB2BGR)
cv2.resizeWindow("window", 3 * 192, 3 * 108)
cv2.imshow('window', imm)
cv2.waitKey(1)
message_pool.pop(0)
except:
print("bug")
thread = threading.Thread(target=ScreenShow, args=())
thread.start()
while True:
screen, address = client.recvfrom(65535)
if(screen.startswith(b"end")):
print("end")
message_pool.append(message)
key = False
elif(screen.startswith(b"start")):
print("start")
message = b""
key=True
elif key:
message += screen
先跑客户端再跑服务端,客户端的端口是随机选用可用端口,不用分别改