我正在测试客户端/服务器剪贴板共享程序(因为RDP没有找到我无法找到的原因)。它工作正常,但当我激活客户端的剪贴板编写代码时,服务器线程在复制后大约20秒崩溃:
_tkinter.TclError:CLIPBOARD选择不存在或形成" STRING"未定义
我做错了什么?这是我的代码,我使用python share_clipboard.py S
和python share_clipboard.py C localhost
在两个命令窗口中运行:
"""
Share clipboard
by Cees Timmerman
01-12-2014 v0.1
"""
import socket, sys, threading
from time import sleep
try: from tkinter import Tk # Python 3
except: from Tkinter import Tk
def dec(s):
return s.decode('utf-8')
def enc(s):
return s.encode('utf-8')
# http://stackoverflow.com/questions/17453212/multi-threaded-tcp-server-in-python
class ClientThread(threading.Thread):
def __init__(my, sock):
threading.Thread.__init__(my)
my.sock = sock
def run(my):
print("Connection from : %s:%s" % (ip, str(port)))
#my.sock.send(enc("\nWelcome to the server\n\n"))
'''
data = "dummydata"
while len(data):
data = dec(clientsock.recv(2048))
print("Client sent : "+data)
my.sock.send(enc("You sent me : "+data))
'''
old_clip = None
while True:
new_clip = tk.clipboard_get()
if new_clip != old_clip:
print("New clip: %r" % new_clip)
old_clip = new_clip
my.sock.sendall(enc(new_clip))
sleep(1)
print("Client disconnected...")
if 1 < len(sys.argv) < 4:
cs = sys.argv[1]
ip = sys.argv[2] if len(sys.argv) == 3 else "0.0.0.0"
else:
print("Usage: %s <C|S> [IP]")
sys.exit()
tk = Tk()
port = 9999
if cs == "S":
tcpsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
tcpsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
tcpsock.bind((ip, port))
threads = []
# Listen for connections.
while True:
tcpsock.listen(4)
print("\nListening for incoming connections...")
(clientsock, (ip, port)) = tcpsock.accept()
newthread = ClientThread(clientsock)
newthread.start()
threads.append(newthread)
# Wait for threads to finish.
for t in threads:
t.join()
else:
clientsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
clientsocket.connect((ip, port))
while True:
data = clientsocket.recv(1024)
print(data)
#tk.withdraw()
#tk.clipboard_clear()
#tk.clipboard_append(data) # Causes error on server: _tkinter.TclError: CLIPBOARD selection doesn't exist or form "STRING" not defined
#tk.destroy()