• 等待网络服务是否可用


    #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 "服务不可用!"
    

      

  • 相关阅读:
    Day05_java方法 方法
    Day05_java流程控制 break、continue
    Day05_java流程控制 循环结构
    Day05_java流程控制 switch选择结构
    Day05_java流程控制结构
    Day04_java流程控制 顺序结构
    Day04_java流程控制 用户交换Scanner
    Day03_java基础 JavaDoc生成文档
    Day03_java基础 包机制
    ltib学习抄录
  • 原文地址:https://www.cnblogs.com/similarface/p/5531032.html
Copyright © 2020-2023  润新知