zoukankan      html  css  js  c++  java
  • 等待网络服务是否可用

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

      

  • 相关阅读:
    Net Remoting(应用程序域)
    C# 方便的复制/比较物件内数据的方法(Object Copy / Compare)
    c# 序列化
    Windows Phone 7 开发日志(初试一、随便研究)
    关于Windows Phone 7推广策略的失误
    vb 托盘图标
    vb code中调用exe文件,当关闭的时候直接关闭文件.
    调用INI文件
    使用SQL的JOB调用DTS定制任务!
    给Word设置目录
  • 原文地址:https://www.cnblogs.com/similarface/p/5531032.html
Copyright © 2011-2022 走看看