You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
59 lines
2.5 KiB
59 lines
2.5 KiB
import json
|
|
import asyncio
|
|
import websockets
|
|
import pyperclip
|
|
import sys, os
|
|
import time
|
|
import subprocess
|
|
|
|
# 获取机器唯一ID,仅适用于Windows系统
|
|
def get_machine_guid():
|
|
if sys.platform == "win32":
|
|
cmd = r'reg query HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Cryptography /v MachineGuid'
|
|
guid = subprocess.check_output(cmd, shell=True).decode().split()[-1]
|
|
return guid
|
|
return None
|
|
|
|
# 加载或创建配置文件,配置文件包含连接WebSocket服务器所需的信息
|
|
def get_config():
|
|
config_file = 'config.json'
|
|
if not os.path.exists(config_file):
|
|
config = {
|
|
'host': '127.0.0.1',
|
|
'port': 8000,
|
|
'key': get_machine_guid() or "default_key" # 使用机器GUID或默认键作为标识
|
|
}
|
|
with open(config_file, 'w', encoding='utf-8') as f:
|
|
json.dump(config, f, indent=2)
|
|
else:
|
|
with open(config_file, 'r', encoding='utf-8') as f:
|
|
config = json.load(f)
|
|
return config
|
|
|
|
# 异步函数,用于持续发送剪贴板数据到服务器
|
|
async def send_clipboard_data(uri, key):
|
|
previous_clipboard_content = "" # 用于追踪剪贴板内容变化
|
|
async with websockets.connect(uri) as websocket: # 异步连接WebSocket服务器
|
|
while True:
|
|
clipboard_content = pyperclip.paste() # 获取当前剪贴板内容
|
|
if clipboard_content and clipboard_content != previous_clipboard_content:
|
|
previous_clipboard_content = clipboard_content # 更新最新的剪贴板内容
|
|
data = {
|
|
'key': key,
|
|
'value': json.dumps({"data": clipboard_content,
|
|
'platform': sys.platform,
|
|
'time': time.strftime('%Y-%m-%d %H:%M:%S')}, ensure_ascii=False)
|
|
}
|
|
await websocket.send(json.dumps(data)) # 发送数据到服务器
|
|
print(f"已更新数据: {data}") # 打印已发送的数据信息
|
|
await asyncio.sleep(1) # 每1秒检查一次剪贴板的变化
|
|
|
|
if __name__ == "__main__":
|
|
config = get_config()
|
|
uri = f"ws://{config.get('host')}:{config.get('port')}/ws" # 构建WebSocket连接URI
|
|
|
|
try:
|
|
print("正在连接到WebSocket服务器...")
|
|
asyncio.get_event_loop().run_until_complete(send_clipboard_data(uri, config.get("key")))
|
|
except Exception as e:
|
|
print(f"发生错误: {e}") # 打印任何异常信息
|
|
|