python之tcp自动重连
操作系统: 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 : 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 " socket error,do reconnect " time.sleep(3) sockLocal = doConnect(host,port) except : print ' other error occur ' time.sleep(3) time.sleep(1) if __name__ == "__main__" : main()
运行效果:
(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
讨论
这里只是个简单的示例代码,实现了python的tcp自动重连。
好,就这些了,希望对你有帮助。
本文github地址:
https://github.com/mike-zhang/mikeBlogEssays/blob/master/2017/20170701_python之tcp自动重连.rst
在写一个传输文件的socket程序时,客户端实现了和服务端断开连接后重新自动连接功能,但是连接上服务端后再重启服务端,客户端出现了Errno 10054异常。出错的代码如下:
client.py:
import socket ip = '192.168.0.124' port = 8000 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) def run(): while True: try: s.connect((ip, port)) # do something:send, recv except socket.error, e: print "get connect error as", e continue s.close() if __name__ == '__main__': run()
解决方案:调整 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)语句的位置,每次重新连接都生成新的socket实例。
client.py:
import socket ip = '192.168.0.124' port = 8000 def run(): while True: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: s.connect((ip, port)) # do something:send, recv except socket.error, e: print "get connect error as", e continue s.close() if __name__ == '__main__': run()