34 lines
976 B
Python
34 lines
976 B
Python
|
|
"""TCP 单次发送客户端:发送 3 条测试消息,验证基本连通性"""
|
||
|
|
|
||
|
|
import socket
|
||
|
|
import time
|
||
|
|
|
||
|
|
HOST = "127.0.0.1"
|
||
|
|
PORT = 8888
|
||
|
|
MESSAGE_COUNT = 3
|
||
|
|
|
||
|
|
|
||
|
|
def send_once(index: int) -> bool:
|
||
|
|
try:
|
||
|
|
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||
|
|
client.settimeout(5)
|
||
|
|
client.connect((HOST, PORT))
|
||
|
|
msg = f"test_message_{index}_{time.time()}"
|
||
|
|
client.send(msg.encode("utf-8"))
|
||
|
|
reply = client.recv(1024)
|
||
|
|
client.close()
|
||
|
|
print(f"消息 {index} 发送成功,回复: {reply.decode('utf-8', errors='replace')}")
|
||
|
|
return True
|
||
|
|
except Exception as exc:
|
||
|
|
print(f"消息 {index} 失败: {exc}")
|
||
|
|
return False
|
||
|
|
|
||
|
|
|
||
|
|
if __name__ == "__main__":
|
||
|
|
print(f"开始连通性测试: 发送 {MESSAGE_COUNT} 条消息到 {HOST}:{PORT}")
|
||
|
|
success = 0
|
||
|
|
for i in range(MESSAGE_COUNT):
|
||
|
|
if send_once(i):
|
||
|
|
success += 1
|
||
|
|
print(f"完成: 成功 {success}/{MESSAGE_COUNT}")
|