使用python實現tcp自動重連

NO IMAGE

作業系統: CentOS 6.9_x64

python語言版本: 2.7.13

問題描述

現有一個tcp客戶端程式,需定期從伺服器取資料,但由於種種原因(網路不穩定等)需要自動重連。

測試伺服器示例程式碼:

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

解決方案


'''
tcp client with reconnect
E-Mail : [email protected]
'''

#! /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()

執行效果:


(py27env) [[email protected] 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

討論

這裡只是個簡單的示例程式碼,實現了python的tcp自動重連。

您可能感興趣的文章:

Python採用socket模擬TCP通訊的實現方法python實現簡單的TCP代理伺服器用Python進行TCP網路程式設計的教程用Python實現一個簡單的多執行緒TCP伺服器的教程python實現TCP伺服器端與客戶端的方法詳解python檢測遠端伺服器tcp埠的方法