国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

使用python實現tcp自動重連

2020-01-04 16:55:42
字體:
來源:轉載
供稿:網友

操作系統: CentOS 6.9_x64

python/103188.html">python語言版本: 2.7.13

問題描述

現有一個tcp客戶端程序,需定期從服務器取數據,但由于種種原因(網絡不穩定等)需要自動重連。

測試服務器示例代碼:

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

解決方案

'''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()

運行效果:

(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

討論

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

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 鄂托克前旗| 遵义市| 五家渠市| 吉安县| 正镶白旗| 苏尼特左旗| 玛纳斯县| 临邑县| 西吉县| 合江县| 云浮市| 普洱| 古蔺县| 承德县| 曲靖市| 夏邑县| 巴彦淖尔市| 育儿| 深水埗区| 绥化市| 厦门市| 上蔡县| 石阡县| 昌吉市| 娱乐| 安国市| 行唐县| 克什克腾旗| 韩城市| 海晏县| 宝应县| 佛教| 怀化市| 崇义县| 柞水县| 芮城县| 祁门县| 祁门县| 博乐市| 济源市| 时尚|