无法通过套接字连接发送pyautogui屏幕截图

时间:2018-06-05 22:13:42

标签: python image sockets tcp pyautogui

我正在尝试通过Python TCP套接字连接发送pyautogui屏幕截图。但是,我有一个小问题。问题是tkinter根本不渲染图像!我认为问题是编码问题,因为我正在编码以UTF-8发送的数据,但我不确定。

这是代码

服务器:

import socket
import pyautogui
import threading

HOST = ""
PORT = 9082
MAX_CONNS = 13
LOCK = threading.Lock()
BUFFSIZE = 16777216

class Server:
    def __init__(self):
        self.conns = []
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.host = HOST
        self.port = PORT
        self.sock.bind((self.host, self.port))
        self.listener()
    def listener(self):
        for x in range(MAX_CONNS):
            self.sock.listen(1)
            self.conn, self.addr = self.sock.accept()
            self.conns.append(self.conn)
            with LOCK:
                print("\n[Info] {} has connected!", self.addr)
            threading.Thread(target=self.recver, args=(self.conn,))
    def recver(self, conn):
        while True:
            data = conn.recv(BUFFSIZE).decode("utf-8")
            if data == "\ncloseconn":
                conn.close()
            else:
                screenshot = pyautogui.screenshot()
                conn.send(str(screenshot).encode("utf-8"))

def main():
    server = Server()

if __name__ == "__main__":
    main()

客户端:

from tkinter import *
import socket
import time
import sys

tk = Tk()
canvas = Canvas(tk, height=640, width=480)
canvas.pack()
tk.resizable(False, False)
tk.title("SystemView")
tk.update()

HOST = sys.argv[1]
PORT = 9082
BUFFSIZE = 16777216
SLEEP_TIME = 0.16666667
SCREENSHOT = "screenshot.gif"

class Client:
    def __init__(self):
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.host = HOST
        self.port = PORT
        self.sock.connect((self.host, self.port))
        self.conn_handle()
    def conn_handle(self):
        while True:
            self.screenshot = self.sock.recv(BUFFSIZE).decode("utf-8")
            f = open(SCREENSHOT, "w")
            f.write(self.screenshot)
            f.close()
            self.render = PhotoImage(file=SCREENSHOT)
            canvas.create_image(0, 0, image=self.render)
            tk.update()
            time.sleep(SLEEP_TIME)

def main():
    client = Client()

if __name__ == "__main__":
    main()
    tk.mainloop()

非常感谢你的帮助, - 马特

0 个答案:

没有答案