Operating system: CentOS 6.9_x64
Python language version: 2.7.13
Problem description
There is a TCP client program that needs to fetch data from the server on a regular basis, but it needs to be automatically re-connected for a variety of reasons (network instability, etc.).
Test Server Sample code:
https://github.com/mike-zhang/pyExamples/blob/master/socketRelate/tcpServer1_multithread.py
Solution Solutions
" "TCP Client with reconnecte-mail: [email protected]" "#!/usr/bin/env python#-*-coding:utf-8-*-ImportOs,sys,timeImportSocketdefDoconnect (host,port): Sock=Socket.socket (socket.af_inet, socket. SOCK_STREAM)Try: Sock.connect ((host,port))except : Pass returnsockdefMain (): Host,port="127.0.0.1", 12345PrintHost,port socklocal=Doconnect (Host,port) whileTrue:Try: Msg=Str (time.time ()) socklocal.send (msg)Print "send msg OK:", msgPrint "recv Data:", SOCKLOCAL.RECV (1024) exceptSocket.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 ()
Operating effect:
(py27env) [[email protected] t1]# python tcpclient1_reconnect.py127.0.0.1 12345send msg OK:1498891374.98recv Data:1498891374.98send msg OK:1498891375.98recv Data:1498891375.98send msg OK:1498891376.98recv data:socket Error, Doreconnectsend msg OK:1498891381.99recv Data:1498891381.99send msg OK:1498891382.99recv Data:1498891382.99
Discuss
Here is a simple example code that implements TCP auto-re-connection for Python.
TCP Auto-re-connection of Python