Python tcp automatic reconnection, python tcp

Source: Internet
Author: User
Tags socket error

Python tcp automatic reconnection, python tcp

Operating System: CentOS 6.9 _ x64

Python version: 2.7.13

Problem description

An existing tcp client program needs to fetch data from the server on a regular basis, but automatic reconnection is required for various reasons (such as network instability.

Sample Code of the test Server:

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

Solution
'''tcp client with reconnectE-Mail : Mike_Zhang@live.com'''#! /usr/bin/env python#-*- coding:utf-8 -*-import os,sys,timeimport socketdef doConnect(host,port):    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)    try :        sock.connect((host,port))    except :        pass    return sockdef 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()

Running effect:

(py27env) [root@local 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,do reconnectsend msg ok :  1498891381.99recv data : 1498891381.99send msg ok :  1498891382.99recv data : 1498891382.99
Discussion

Here is just a simple example code that implements the python tcp automatic reconnection.

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.