鼠标遥控器

时间:2018-04-10 20:27:11

标签: python sockets udp mouse pyautogui

尝试使用PyAutoGui和socket通信在python上实现某种synergy。 其思想是使用服务器计算机的鼠标/键盘控制LAN上另一台计算机的鼠标和键盘。 到目前为止,它只是鼠标移动实现。 以下是一些课程:

服务器部分:

class Server:
    def __init__(self):
        self.s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.ip = get_ip()
        self.port = 3000
        self.transfer_mod = False
        self.client_address = ""

    def start(self):
        print("Started server with ip: {}".format(self.ip))
        self.s.bind((self.ip, self.port))
        self.get_connection()

    def get_connection(self):
        print("Waiting for connection...")
        while True:
            request, self.client_address = self.s.recvfrom(4096)
            if request:
                self.s.sendto(request, self.client_address)
                print("{} connected!".format(self.client_address))
                break

    def enable_transfer(self):
        print("Transfer to {} enabled".format(self.client_address))
        self.transfer_mod = True
        transfer_thread = threading.Thread(target=self.transfer_mouse)
        transfer_thread.start()

    def disable_transfer(self):
        print("Transfer to {} disabled".format(self.client_address))
        self.transfer_mod = False

    def transfer_mouse(self):
        previous_pos = (-1, -1)
        while self.transfer_mod:
            pos = pyautogui.position()

            if pos != previous_pos:
                data = pickle.dumps(pos)
                self.s.sendto(data, self.client_address)
                sleep(0.1)

            previous_pos = pos

    def close(self):
        self.disable_transfer()
        self.s.close()

客户端部分:

class Client:
    def __init__(self):
        self.s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.port = 3000
        self.connection = False

    def connect(self, server_ip):
        request = bytes("Request","utf-8")
        self.s.sendto(request, (server_ip, self.port))
        received, address = self.s.recvfrom(4096)
        if received == request:
            print("Connected to {}".format(server_ip))
            self.connection = True
            threading.Thread(target=self.receive_data).start()

    def receive_data(self):
        while self.connection:
            data, server = self.s.recvfrom(4096)
            pos = pickle.loads(data)
            self.control_mouse(pos)

    def disconnect(self):
        print("Disconnected from the server")
        self.connection = False

    def control_mouse(self, position):
        pyautogui.moveTo(position[0], position[1])

    def close(self):
        self.disconnect()
        self.s.close()

因此,问题在于客户端计算机上鼠标移动的速度非常低。似乎有太多超过数据包或类似的东西。所以,问题本身:这是实现这个想法的好方法,如果是的话,该脚本的问题是什么,如果没有,有关如何更正确地做到这一点的任何建议吗?

0 个答案:

没有答案