TCP Auto-re-connection of Python

Source: Internet
Author: User
Tags socket error

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.