当前位置: 首页>>代码示例>>Python>>正文


Python Zeroconf.unregister_service方法代码示例

本文整理汇总了Python中zeroconf.Zeroconf.unregister_service方法的典型用法代码示例。如果您正苦于以下问题:Python Zeroconf.unregister_service方法的具体用法?Python Zeroconf.unregister_service怎么用?Python Zeroconf.unregister_service使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在zeroconf.Zeroconf的用法示例。


在下文中一共展示了Zeroconf.unregister_service方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_integration

# 需要导入模块: from zeroconf import Zeroconf [as 别名]
# 或者: from zeroconf.Zeroconf import unregister_service [as 别名]
def test_integration():
    service_added = Event()
    service_removed = Event()

    type_ = "_http._tcp.local."
    registration_name = "xxxyyy.%s" % type_

    def on_service_state_change(zeroconf, service_type, state_change, name):
        if name == registration_name:
            if state_change is ServiceStateChange.Added:
                service_added.set()
            elif state_change is ServiceStateChange.Removed:
                service_removed.set()

    zeroconf_browser = Zeroconf()
    browser = ServiceBrowser(zeroconf_browser, type_, [on_service_state_change])

    zeroconf_registrar = Zeroconf()
    desc = {'path': '/~paulsm/'}
    info = ServiceInfo(
        type_, registration_name,
        socket.inet_aton("10.0.1.2"), 80, 0, 0,
        desc, "ash-2.local.")
    zeroconf_registrar.register_service(info)

    try:
        service_added.wait(1)
        assert service_added.is_set()
        zeroconf_registrar.unregister_service(info)
        service_removed.wait(1)
        assert service_removed.is_set()
    finally:
        zeroconf_registrar.close()
        browser.cancel()
        zeroconf_browser.close()
开发者ID:justingiorgi,项目名称:python-zeroconf,代码行数:37,代码来源:test_zeroconf.py

示例2: advertise

# 需要导入模块: from zeroconf import Zeroconf [as 别名]
# 或者: from zeroconf.Zeroconf import unregister_service [as 别名]
    def advertise(self):
        postfix = self.config['global']['service_prefix']
        self.port = int(self.config['global']['port'])
        #print(self.config['device']['hostname']+postfix)
        info = ServiceInfo(postfix, self.config['device']['hostname']+"."+postfix,
                       socket.inet_aton(self.ip), self.port, 0, 0,
                       {'info': self.config['device']['description']}, "hazc.local.")

        self.bindConnection()

        zeroconf = Zeroconf()
        zeroconf.register_service(info)


        try:
            while True:
#                 try:
                print("Ready")
                self.conn, self.addr = self.webcontrol.accept()
                self.listen()
                self.conn.close()
        except KeyboardInterrupt:
            pass
        finally:
            print()
            print("Unregistering...")
            zeroconf.unregister_service(info)
            zeroconf.close()

        try:
            print("Shutting down socket")
            self.webcontrol.shutdown(socket.SHUT_RDWR)
        except Exception as e:
            print(e)
开发者ID:ArcAwe,项目名称:hazc,代码行数:36,代码来源:hazc_device.py

示例3: GlancesAutoDiscoverClient

# 需要导入模块: from zeroconf import Zeroconf [as 别名]
# 或者: from zeroconf.Zeroconf import unregister_service [as 别名]
class GlancesAutoDiscoverClient(object):

    """Implementation of the zeroconf protocol (client side for the Glances server)."""

    def __init__(self, hostname, args=None):
        if zeroconf_tag:
            zeroconf_bind_address = args.bind_address
            try:
                self.zeroconf = Zeroconf()
            except socket.error as e:
                logger.error("Cannot start zeroconf: {}".format(e))

            # XXX *BSDs: Segmentation fault (core dumped)
            # -- https://bitbucket.org/al45tair/netifaces/issues/15
            if not BSD:
                try:
                    # -B @ overwrite the dynamic IPv4 choice
                    if zeroconf_bind_address == '0.0.0.0':
                        zeroconf_bind_address = self.find_active_ip_address()
                except KeyError:
                    # Issue #528 (no network interface available)
                    pass

            # Check IP v4/v6
            address_family = socket.getaddrinfo(zeroconf_bind_address, args.port)[0][0]

            # Start the zeroconf service
            self.info = ServiceInfo(
                zeroconf_type, '{}:{}.{}'.format(hostname, args.port, zeroconf_type),
                address=socket.inet_pton(address_family, zeroconf_bind_address),
                port=args.port, weight=0, priority=0, properties={}, server=hostname)
            try:
                self.zeroconf.register_service(self.info)
            except socket.error as e:
                logger.error("Error while announcing Glances server: {}".format(e))
            else:
                print("Announce the Glances server on the LAN (using {} IP address)".format(zeroconf_bind_address))
        else:
            logger.error("Cannot announce Glances server on the network: zeroconf library not found.")

    @staticmethod
    def find_active_ip_address():
        """Try to find the active IP addresses."""
        import netifaces
        # Interface of the default gateway
        gateway_itf = netifaces.gateways()['default'][netifaces.AF_INET][1]
        # IP address for the interface
        return netifaces.ifaddresses(gateway_itf)[netifaces.AF_INET][0]['addr']

    def close(self):
        if zeroconf_tag:
            self.zeroconf.unregister_service(self.info)
            self.zeroconf.close()
开发者ID:nicolargo,项目名称:glances,代码行数:55,代码来源:autodiscover.py

示例4: ZeroconfService

# 需要导入模块: from zeroconf import Zeroconf [as 别名]
# 或者: from zeroconf.Zeroconf import unregister_service [as 别名]
class ZeroconfService(AbstractZeroconfService):
    """
    :class:`ZeroconfService` uses `python zeroconf`_

    .. _python zeroconf: https://pypi.org/project/zeroconf/

    Install::

    .. code-block:: bash

        pip install zeroconf
    """

    def __init__(self, name, port):
        super(ZeroconfService, self).__init__(name, port)

        self._zeroconf = None
        self._infos = []

    @classmethod
    def has_support(cls):
        return support

    def start(self):
        self._zeroconf = Zeroconf()
        for index, ip in enumerate(self.ips):
            info = self._gerenate_service_info(index, ip)
            self._infos.append(info)

            self._zeroconf.register_service(info)
            self._log('Zeroconf {} - Registered service: name={}, regtype={}, domain={}', self.__class__.__name__,
                      self.name, self.type, 'local.')
            self._log('         Network: {}', ip)

    def _gerenate_service_info(self, index, ip):
        name = '{}-{}.{}.local.'.format(self.name.lower(), index, self.type, '.local.')

        return ServiceInfo(
            self.type + '.local.',
            name,
            socket.inet_aton(ip),
            self.port,
            0,
            0,
            {}
        )

    def close(self):
        for info in self._infos:
            self._zeroconf.unregister_service(info)
开发者ID:PedalPi,项目名称:WebService,代码行数:52,代码来源:zeroconf_service.py

示例5: createService

# 需要导入模块: from zeroconf import Zeroconf [as 别名]
# 或者: from zeroconf.Zeroconf import unregister_service [as 别名]
def createService():

    zeroconf = Zeroconf()
    # Look up info's __init__ in python-zeroconf's documentation #
    info = ServiceInfo("_http._tcp.local.", "Takiyaki._http._tcp.local.", socket.inet_aton(socket.gethostbyname(socket.gethostname())), 8080,0,0,socket.gethostname() + ".local.")
    # Server is supported but not compulsory, set server as inputted name #
    print "Registered Service [" + info.name + "]"
    zeroconf.register_service(info)

    try:
        while True: sleep(0.1)
    except KeyboardInterrupt:
        zeroconf.unregister_service(info)
        print("Unregistered")
        zeroconf.close()
    print("Service registered")
    zeroconf.close()
开发者ID:merchat7,项目名称:LAN-Single-File-Distributor,代码行数:19,代码来源:trackerReg.py

示例6: GlancesAutoDiscoverClient

# 需要导入模块: from zeroconf import Zeroconf [as 别名]
# 或者: from zeroconf.Zeroconf import unregister_service [as 别名]
class GlancesAutoDiscoverClient(object):

    """Implementation of the zeroconf protocol (client side for the Glances server)."""

    def __init__(self, hostname, args=None):
        if zeroconf_tag:
            zeroconf_bind_address = args.bind_address
            try:
                self.zeroconf = Zeroconf()
            except socket.error as e:
                logger.error("Cannot start zeroconf: {0}".format(e))

            try:
                # -B @ overwrite the dynamic IPv4 choice
                if zeroconf_bind_address == '0.0.0.0':
                    zeroconf_bind_address = self.find_active_ip_address()
            except KeyError:
                # Issue #528 (no network interface available)
                pass

            print("Announce the Glances server on the LAN (using {0} IP address)".format(zeroconf_bind_address))
            self.info = ServiceInfo(
                zeroconf_type, '{0}:{1}.{2}'.format(hostname, args.port, zeroconf_type),
                address=socket.inet_aton(zeroconf_bind_address), port=args.port,
                weight=0, priority=0, properties={}, server=hostname)
            self.zeroconf.register_service(self.info)
        else:
            logger.error("Cannot announce Glances server on the network: zeroconf library not found.")

    @staticmethod
    def find_active_ip_address():
        """Try to find the active IP addresses."""
        if not 'freebsd' in sys.platform:
            import netifaces
            # Interface of the default gateway
            gateway_itf = netifaces.gateways()['default'][netifaces.AF_INET][1]
            # IP address for the interface
            return netifaces.ifaddresses(gateway_itf)[netifaces.AF_INET][0]['addr']
        else:
            raise KeyError, 'On FreeBSD, this would segfault'

    def close(self):
        if zeroconf_tag:
            self.zeroconf.unregister_service(self.info)
            self.zeroconf.close()
开发者ID:hank,项目名称:glances,代码行数:47,代码来源:glances_autodiscover.py

示例7: GlancesAutoDiscoverClient

# 需要导入模块: from zeroconf import Zeroconf [as 别名]
# 或者: from zeroconf.Zeroconf import unregister_service [as 别名]
class GlancesAutoDiscoverClient(object):

    """Implementation of the zeroconf protocol (client side for the Glances server)."""

    def __init__(self, hostname, args=None):
        if zeroconf_tag:
            zeroconf_bind_address = args.bind_address
            try:
                self.zeroconf = Zeroconf()
            except socket.error as e:
                logger.error("Cannot start zeroconf: {0}".format(e))

            if netifaces_tag:
                # -B @ overwrite the dynamic IPv4 choice
                if zeroconf_bind_address == '0.0.0.0':
                    zeroconf_bind_address = self.find_active_ip_address()
            else:
                logger.error("Couldn't find the active IP address: netifaces library not found.")

            logger.info("Announce the Glances server on the LAN (using {0} IP address)".format(zeroconf_bind_address))
            print("Announce the Glances server on the LAN (using {0} IP address)".format(zeroconf_bind_address))

            self.info = ServiceInfo(
                zeroconf_type, '{0}:{1}.{2}'.format(hostname, args.port, zeroconf_type),
                address=socket.inet_aton(zeroconf_bind_address), port=args.port,
                weight=0, priority=0, properties={}, server=hostname)
            self.zeroconf.register_service(self.info)
        else:
            logger.error("Cannot announce Glances server on the network: zeroconf library not found.")

    def find_active_ip_address(self):
        """Try to find the active IP addresses."""
        try:
            # Interface of the default gateway
            gateway_itf = netifaces.gateways()['default'][netifaces.AF_INET][1]
            # IP address for the interface
            return netifaces.ifaddresses(gateway_itf)[netifaces.AF_INET][0]['addr']
        except Exception:
            return None

    def close(self):
        if zeroconf_tag:
            self.zeroconf.unregister_service(self.info)
            self.zeroconf.close()
开发者ID:SpaceAppsXploration,项目名称:glances,代码行数:46,代码来源:glances_autodiscover.py

示例8: Advertisement

# 需要导入模块: from zeroconf import Zeroconf [as 别名]
# 或者: from zeroconf.Zeroconf import unregister_service [as 别名]
class Advertisement(object):
    def __init__(self, ip=None):
        """
        :ip: if string `ip` given, register on given IP
             (if None: default route's IP).
        """
        self.zeroconf = Zeroconf()
        self.info = build_service_info(ip=ip or main_ip())

    def register(self):
        """Registers the service on the network.
        """
        self.zeroconf.register_service(self.info)
        log.debug("Registered {} on {}:{}".format(self.info.name,
                                                   self.ip,
                                                   self.info.port))

    def unregister(self):
        """Unregisters the service.
        """
        self.zeroconf.unregister_service(self.info)
        log.debug("Unregistered touchoscbridge.")

    def update(self, ip=None):
        """Re-register the the service on the network.

        :ip: if string `ip` is given, use given IP when registering.
        """
        self.unregister()
        self.info = build_service_info(ip=ip or main_ip())
        self.register()

    def close(self):
        """Free resources.
        Advertisement.unregister() should be called before closing.
        """
        self.zeroconf.close()

    def get_ip(self):
        """:return: the service's IP as a string.
        """
        return socket.inet_ntoa(self.info.address)

    ip = property(get_ip)
开发者ID:SpotlightKid,项目名称:touchosc2midi,代码行数:46,代码来源:advertise.py

示例9: __init__

# 需要导入模块: from zeroconf import Zeroconf [as 别名]
# 或者: from zeroconf.Zeroconf import unregister_service [as 别名]
class ServiceDiscoveryServer:

    def __init__(self, port):
        inet = netifaces.AF_INET
        hostname = socket.gethostname()
        def_gw = netifaces.gateways()['default'][inet][1]
        addr = netifaces.ifaddresses(def_gw)[inet][0]['addr']
        addr = socket.inet_aton(addr)
        self.zeroconf = Zeroconf()
        self.info = ServiceInfo(
            SRV_TYPE, srv_fqname(), addr, port, 0, 0,
            {}, '{}.local.'.format(hostname)
        )

    def start(self):
        self.zeroconf.register_service(self.info)

    def stop(self):
        self.zeroconf.unregister_service(self.info)
        self.zeroconf.close()
开发者ID:cailloumajor,项目名称:pilotwire-controller,代码行数:22,代码来源:zeroconf.py

示例10: bootstrap

# 需要导入模块: from zeroconf import Zeroconf [as 别名]
# 或者: from zeroconf.Zeroconf import unregister_service [as 别名]
    def bootstrap(self):
        try:
            zeroconf = Zeroconf(interfaces=[ self.bootstrap_ip ])
            self._log.debug('Zeroconf instantiated.')
        except:
            self._log.error('Error instantiating zeroconf instance on interface: {0} with IP: {1}'.format(self.iface, self.bootstrap_ip))
            raise

        try:
            zeroconf.register_service(self.service_discovery_def)
            discovery_browser = ServiceBrowser(zeroconf, self.service_discovery_type, handlers=[ self._election_handler ])
            leader_browser = ServiceBrowser(zeroconf, self.service_leader_type, handlers=[ self._election_handler ])
        except:
            self._log.error('Error encountered with registered zeroconf services or browser.')
            raise

        while True:
            sleep(.1)
            if self._discovery_peer_count <= 0:
                log.debug('All peers unregistered from discovery service.')
                break

        if self.election_id == self._leader_id:
            zeroconf.unregister_service(self.service_leader_def)
            self._log.debug('Leader service unregistered.')

        sleep(1)
        try:
            zeroconf.close()
        except:
            self._log.error('Error encountered closing zerconf instance.')
            raise

        self._log.debug('Zerconf instance close.')

        if self.election_id == self._leader_id:
            bootstrap_command = [ self.action ] + self.get_peer_addresses(self._peers)
            self._log.info('Leader performing bootstrap action: {}'.format(' '.join(bootstrap_command)))
            Popen(bootstrap_command)
开发者ID:mrbobbytables,项目名称:zeroinit,代码行数:41,代码来源:bootstrap.py

示例11: test_integration

# 需要导入模块: from zeroconf import Zeroconf [as 别名]
# 或者: from zeroconf.Zeroconf import unregister_service [as 别名]
def test_integration():
    service_added = Event()
    service_removed = Event()

    type_ = "_http._tcp.local."
    registration_name = "xxxyyy.%s" % type_

    class MyListener(object):

        def remove_service(self, zeroconf, type_, name):
            if name == registration_name:
                service_removed.set()

        def add_service(self, zeroconf, type_, name):
            if name == registration_name:
                service_added.set()

    zeroconf_browser = Zeroconf()
    listener = MyListener()
    browser = ServiceBrowser(zeroconf_browser, type_, listener)

    zeroconf_registrar = Zeroconf()
    desc = {'path': '/~paulsm/'}
    info = ServiceInfo(
        type_, registration_name,
        socket.inet_aton("10.0.1.2"), 80, 0, 0,
        desc, "ash-2.local.")
    zeroconf_registrar.register_service(info)

    try:
        service_added.wait(1)
        assert service_added.is_set()
        zeroconf_registrar.unregister_service(info)
        service_removed.wait(1)
        assert service_removed.is_set()
    finally:
        zeroconf_registrar.close()
        browser.cancel()
        zeroconf_browser.close()
开发者ID:esazhin,项目名称:python-zeroconf,代码行数:41,代码来源:test_zeroconf.py

示例12: ZstStage

# 需要导入模块: from zeroconf import Zeroconf [as 别名]
# 或者: from zeroconf.Zeroconf import unregister_service [as 别名]
class ZstStage(ZstNode):

    def __init__(self, stageName="stage", port=6000):
        ZstNode.__init__(self, stageName)
        self.zeroconf = Zeroconf()

        address = "tcp://*:" + str(port)
        self.reply.socket.bind(address)

        desc = {'name': self.name}
        addr = socket.gethostbyname(socket.gethostname())
        servicename = "ShowtimeStage"
        self.stageServiceInfo = ServiceInfo("_zeromq._tcp.local.",
           servicename + "._zeromq._tcp.local.",
           socket.inet_aton(addr), port, 0, 0,
           desc)
        self.zeroconf.register_service(self.stageServiceInfo)
        print("Stage active on address " + str(self.reply.socket.getsockopt(zmq.LAST_ENDPOINT)))
        
    def close(self):
        self.zeroconf.unregister_service(self.stageServiceInfo)
        self.zeroconf.close()
        ZstNode.close(self)
开发者ID:Mystfit,项目名称:Showtime-Python,代码行数:25,代码来源:zst_stage.py

示例13: Zeroconf

# 需要导入模块: from zeroconf import Zeroconf [as 别名]
# 或者: from zeroconf.Zeroconf import unregister_service [as 别名]
class Zeroconf(object):
    """ A simple class to publish a network service using zeroconf. """

    def __init__(self, name, port, **kwargs):
        self.zconf = None
        stype = kwargs.get('stype', "_http._tcp.local.")

        full_name = name
        if not name.endswith('.'):
            full_name += '.' + stype

        props = {'txtvers': '1',
                 'iTSh Version': '131073', #'196609'
                 'Machine Name': name,
                 'Password': '0'}

        self.svc_info = ServiceInfo(stype,
                                    full_name,
                                    find_local_ipaddress(),
                                    port,
                                    0,
                                    0,
                                    props)

    def publish(self):
        """ Publish the service to the network. """
        if self.zconf is None:
            self.zconf = ZeroC()
            self.zconf.register_service(self.svc_info)

    def unpublish(self):
        """ Tell the network we're closed :-) """
        if self.zconf is not None:
            self.zconf.unregister_service(self.svc_info)
            self.zconf.close()
            self.zconf = None
开发者ID:zathras777,项目名称:spydaap,代码行数:38,代码来源:zeroconf_local.py

示例14: len

# 需要导入模块: from zeroconf import Zeroconf [as 别名]
# 或者: from zeroconf.Zeroconf import unregister_service [as 别名]
    logging.basicConfig(level=logging.DEBUG)
    if len(sys.argv) > 1:
        assert sys.argv[1:] == ['--debug']
        logging.getLogger('zeroconf').setLevel(logging.DEBUG)

    # Test a few module features, including service registration, service
    # query (for Zoe), and service unregistration.
    print("Multicast DNS Service Discovery for Python, version %s" % (__version__,))
    r = Zeroconf()
    print("1. Testing registration of a service...")
    desc = {'version': '0.10', 'a': 'test value', 'b': 'another value'}
    info = ServiceInfo("_http._tcp.local.",
                       "My Service Name._http._tcp.local.",
                       socket.inet_aton("127.0.0.1"), 1234, 0, 0, desc)
    print("   Registering service...")
    r.register_service(info)
    print("   Registration done.")
    print("2. Testing query of service information...")
    print("   Getting ZOE service: %s" % (
        r.get_service_info("_http._tcp.local.", "ZOE._http._tcp.local.")))
    print("   Query done.")
    print("3. Testing query of own service...")
    queried_info = r.get_service_info("_http._tcp.local.", "My Service Name._http._tcp.local.")
    assert queried_info
    print("   Getting self: %s" % (queried_info,))
    print("   Query done.")
    print("4. Testing unregister of service information...")
    r.unregister_service(info)
    print("   Unregister done.")
    r.close()
开发者ID:LRSEngineering,项目名称:python-zeroconf,代码行数:32,代码来源:self_test.py

示例15: len

# 需要导入模块: from zeroconf import Zeroconf [as 别名]
# 或者: from zeroconf.Zeroconf import unregister_service [as 别名]
import logging
import socket
import sys
from time import sleep

from zeroconf import ServiceInfo, Zeroconf

if __name__ == '__main__':
    logging.basicConfig(level=logging.DEBUG)
    if len(sys.argv) > 1:
        assert sys.argv[1:] == ['--debug']
        logging.getLogger('zeroconf').setLevel(logging.DEBUG)

    desc = {'version': '0.1'}
    info = ServiceInfo("_http._tcp.local.",
                       "pispotify._http._tcp.local.",
                       socket.inet_aton("192.168.0.17"), 80, 0, 0, desc) #use the right ip
    
    zeroconf = Zeroconf()
    print("Registration of a service, press Ctrl-C to exit...")
    zeroconf.register_service(info)
    try:
        while True:
            sleep(0.1)
    except KeyboardInterrupt:
        pass
    finally:
        print("Unregistering...")
        zeroconf.unregister_service(info)
        zeroconf.close()
开发者ID:meteran,项目名称:tir-PiSpotify,代码行数:32,代码来源:sd.py


注:本文中的zeroconf.Zeroconf.unregister_service方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。