Files
cjgc_data/page_objects/call_xie.py
2026-03-12 17:03:56 +08:00

46 lines
1.6 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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")