当前位置:   article > 正文

Python Socket 客户端实现,支持掉线重连_python socket断线重连

python socket断线重连
  1. # 导入socket库
  2. import socket
  3. import threading
  4. import time
  5. import datetime
  6. class SocketClient:
  7. def __init__(self, ip, port):
  8. self.IP = ip
  9. self.PORT = port
  10. """ socket 建立链接 """
  11. def connect(self):
  12. while True:
  13. server2 = (self.IP, self.PORT)
  14. global socket_client2
  15. socket_client2 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  16. try:
  17. socket_client2.connect(server2)
  18. except Exception as message:
  19. print('连接服务器报错%s' % message)
  20. time.sleep(1)
  21. continue
  22. else:
  23. print('连接服务器成功')
  24. threading.Thread(target=self._recv).start()
  25. break
  26. """ socket发送数据 """
  27. def _send(self, msg):
  28. try:
  29. socket_client2.send(msg.encode("gbk"))
  30. print('发送给服务器的消息:%s' % msg)
  31. except Exception as message:
  32. print('连接服务器报错%s' % message)
  33. self.connect()
  34. """ socket接收数据 """
  35. def _recv(self):
  36. try:
  37. while (True):
  38. res = socket_client2.recv(1024)
  39. if not res:
  40. break
  41. print(datetime.datetime.now().strftime('%Y-%m-%d_%H_%M_%S') + ' 收到服务器的消息:%s' % res)
  42. except Exception as message:
  43. print('收到服务器的消息报错%s' % message)
  44. self.connect();
  45. if __name__ == '__main__':
  46. client = SocketClient("192.168.2.122", 2024);
  47. client.connect()

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/繁依Fanyi0/article/detail/91432
推荐阅读
相关标签
  

闽ICP备14008679号