当前位置:   article > 正文

【python socket】TCP客户端断线重连_python socket断线重连

python socket断线重连

主要思想:用一个线程每1s发一组数据,判断当前服务端是否还存活,如果活着就等1s再继续发数据,如果服务端挂了就等2s重新connect

  1. def Thread_ConnectSocket_CAN():
  2. while True:
  3. try:
  4. global tcp_client_socket_CAN
  5. tcp_client_socket_CAN = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  6. tcp_client_socket_CAN.connect(("127.0.0.1", 6000))
  7. while True:
  8. try:
  9. sendData = "7E7EC2880001004BAA55"
  10. tcp_client_socket_CAN.send(bytes.fromhex(sendData))
  11. time.sleep(1)
  12. except:
  13. break
  14. except socket.error:
  15. print("未连接,尝试重连中..")
  16. time .sleep(2)
  17. except Exception as e:
  18. print(e)
  19. time.sleep(2)
  20. if __name__ == '__main__':
  21. # 启动线程
  22. thread_obj_CAN = threading.Thread(target=Thread_ConnectSocket_CAN)
  23. thread_obj_CAN.setDaemon(True)
  24. thread_obj_CAN.start()
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/盐析白兔/article/detail/91417
推荐阅读
相关标签
  

闽ICP备14008679号