【python socket】TCP客户端断线重连
主要思想:用一个线程每1s发一组数据,判断当前服务端是否还存活,如果活着就等1s再继续发数据,如果服务端挂了就等2s重新connect
·
主要思想:用一个线程每1s发一组数据,判断当前服务端是否还存活,如果活着就等1s再继续发数据,如果服务端挂了就等2s重新connect
def Thread_ConnectSocket_CAN():
while True:
try:
global tcp_client_socket_CAN
tcp_client_socket_CAN = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
tcp_client_socket_CAN.connect(("127.0.0.1", 6000))
while True:
try:
sendData = "7E7EC2880001004BAA55"
tcp_client_socket_CAN.send(bytes.fromhex(sendData))
time.sleep(1)
except:
break
except socket.error:
print("未连接,尝试重连中..")
time .sleep(2)
except Exception as e:
print(e)
time.sleep(2)
if __name__ == '__main__':
# 启动线程
thread_obj_CAN = threading.Thread(target=Thread_ConnectSocket_CAN)
thread_obj_CAN.setDaemon(True)
thread_obj_CAN.start()
更多推荐
已为社区贡献11条内容
所有评论(0)