python is used to realize tcp automatic reconnection

  • 2020-06-07 04:50:27
  • OfStack

Operating system: CentOS 6.9_x64

python version: 2.7.13

Problem description

There is an tcp client program that needs to fetch data from the server on a regular basis, but needs automatic reconnection due to various reasons (network instability, etc.).

Test server sample code:

https://github.com/mike-zhang/pyExamples/blob/master/socketRelate/tcpServer1_multithread.py

The solution


'''
tcp client with reconnect
E-Mail : Mike_Zhang@live.com
'''

#! /usr/bin/env python
#-*- coding:utf-8 -*-

import os,sys,time
import socket

def doConnect(host,port):
  sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  try :
    sock.connect((host,port))
  except :
    pass
  return sock

def main():
  host,port = "127.0.0.1",12345
  print host,port
  sockLocal = doConnect(host,port)

  while True :
    try :
      msg = str(time.time())
      sockLocal.send(msg)
      print "send msg ok : ",msg
      print "recv data :",sockLocal.recv(1024)
    except socket.error :
      print "\r\nsocket error,do reconnect "
      time.sleep(3)
      sockLocal = doConnect(host,port)
    except :
      print '\r\nother error occur '
      time.sleep(3)
    time.sleep(1)

if __name__ == "__main__" :
  main()

Operation effect:


(py27env) [root@local t1]# python tcpClient1_reconnect.py
127.0.0.1 12345
send msg ok : 1498891374.98
recv data : 1498891374.98
send msg ok : 1498891375.98
recv data : 1498891375.98
send msg ok : 1498891376.98
recv data :

socket error,do reconnect
send msg ok : 1498891381.99
recv data : 1498891381.99
send msg ok : 1498891382.99
recv data : 1498891382.99

discuss

This is just a simple example code that implements tcp automatic reconnection of python.


Related articles: