import socket def send_tcp_command(command: str, host: str = '127.0.0.1', port: int = 8888, encoding: str = 'utf-8') -> bool: """ 向指定TCP端口发送指令 参数: command: 要发送的指令字符串 host: 目标主机地址(默认127.0.0.1) port: 目标端口(默认8888) encoding: 字符串编码格式(默认utf-8) 返回: 发送成功返回True,失败返回False """ # 创建TCP socket并自动关闭(with语句确保资源释放) with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock: try: # 连接服务器(超时时间5秒,避免无限阻塞) sock.settimeout(5.0) sock.connect((host, port)) # 发送指令(转换为字节流) sock.sendall(command.encode(encoding)) print(f"指令 '{command}' 发送成功") return True except ConnectionRefusedError: print(f"连接失败:{host}:{port} 未监听或不可达") except socket.timeout: print(f"连接超时:超过5秒未连接到 {host}:{port}") except UnicodeEncodeError: print(f"编码失败:指令包含{encoding}无法编码的字符") except Exception as e: print(f"发送失败:{str(e)}") return False # 使用示例 if __name__ == "__main__": # 发送StartConnect指令 send_tcp_command("StartConnect") # 也可以发送其他指令,例如: # send_tcp_command("StopConnect")