import socket
import time
# 设备信息
ip_address = '192.168.10.11'
port = 5020
def check_connection(ip, port):
try:
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.settimeout(1) # 设置超时时间为1秒
client_socket.connect((ip, port))
client_socket.close()
return True
except Exception as e:
return False
try:
while True:
connection_status = check_connection(ip_address, port)
if connection_status:
print("设备连接成功.")
else:
print("设备连接失败!")
time.sleep(1) # 暂停5秒后继续循环
except KeyboardInterrupt:
# 当用户按下Ctrl+C时,终止循环并关闭连接
pass
# 关闭连接
# client_socket.close()
定期检查MODBUS TCP设备与客户端的连接状态
最新推荐文章于 2025-04-21 12:04:59 发布