等待网络服务是否可用
2016-05-26 14:41
253 查看
#coding:utf-8 __author__ = 'similarface' import argparse import socket import errno from time import time as now DEFAULT_TIMEOUT = 120 DEFAULT_SERVER_HOST = 'localhost' DEFAULT_SERVER_PORT = 80 class NetServiceChecker(object): """ Wait for a network service to come online""" def __init__(self, host, port, timeout=DEFAULT_TIMEOUT): self.host = host self.port = port self.timeout = timeout self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) def end_wait(self): self.sock.close() def check(self): """ Check the service """ if self.timeout: #超时时间间隔+加上现在的时间 end_time = now() + self.timeout while True: try: if self.timeout: #下一次的超时时间 next_timeout = end_time - now() if next_timeout < 0: return False else: print "设置soct的timeout参数 %ss" %round(next_timeout) self.sock.settimeout(next_timeout) #连接sock self.sock.connect((self.host, self.port)) # handle exceptions except socket.timeout, err: if self.timeout: return False except socket.error, err: print "Exception: %s" %err else: #如果soct能建立 self.end_wait() return True if __name__ == '__main__': parser = argparse.ArgumentParser(description='Wait for Network Service') parser.add_argument('--host', action="store", dest="host", default=DEFAULT_SERVER_HOST) parser.add_argument('--port', action="store", dest="port", type=int, default=DEFAULT_SERVER_PORT) parser.add_argument('--timeout', action="store", dest="timeout", type=int, default=DEFAULT_TIMEOUT) given_args = parser.parse_args() host, port, timeout = given_args.host, given_args.port, given_args.timeout service_checker = NetServiceChecker(host, port, timeout=timeout) print "检测网络服务 %s:%s ..." %(host, port) if service_checker.check(): print "服务可用!" else: print "服务不可用!"
相关文章推荐
- android网络安全
- Android网络开发之实时获取最新数据
- BP神经网络
- Android studio加载网络权限
- android 判断当前环境网络是否可用及获取当前网络类型
- 使用ICMP协议Ping网络主机
- https 双向认证
- Volley框架的基本解读(八)
- Android 中 HttpURLConnection 使用详解
- HTTP缓存技术,304(Not Modified)和200(from cache)区别
- HTTP客户端操作工具类
- http - referer
- 各类 HTTP 返回状态代码详解
- TCP沾包解包(3)
- 负载平衡问题[网络流24题之19]
- 网络工具类
- Andriod开发 网络状态改变监听(这样说可能不太合理)
- TCP沾包解包(2)
- Linux下使用iptables禁止指定IP地址的网络连接
- http长连接