1

按照此示例 ,我想在获取所有元素并将它们返回列表时停止服务。

停止无限循环就是调用gobject.MainLoop().quit(),但不知道何时何地调用。谢谢

4

2 回答 2

2

当现在的最后一个服务到达时,您需要停止服务浏览。这将为您提供当前可用服务的快照。

C 层中有一个标志,可让您检查是否有更多服务即将推出。它被称为AVAHI_BROWSER_ALL_FOR_NOW。我不熟悉python绑定,但也许可以在回调的stypeor参数中以某种方式检查这个标志?flags

当你看到这个标志被设置时 - 调用gobject.MainLoop().quit()

于 2011-03-12T07:58:36.330 回答
1

您还需要收听AllForNow信号。还要考虑CacheExhaustedFailureorg.freedesktop.Avahi.ServiceBrowser的接口在这里声明。

在我的机器上运行以下命令会在大约一秒钟后返回并打印:

browsing ...
cache exhausted
New service: name = Lexmark X264dn; address = 10.9.0.93; port = 80
that's all for now
done
0:00:01.004258

希望能帮助到你!


from _dbus_glib_bindings import DBusGMainLoop
import dbus, avahi
import gobject

class ServiceBrowser():
    def __init__(self, service):
        loop = DBusGMainLoop(set_as_default=True)

        bus = dbus.SystemBus(mainloop=loop)

        self._server = dbus.Interface(bus.get_object(avahi.DBUS_NAME, avahi.DBUS_PATH_SERVER), avahi.DBUS_INTERFACE_SERVER)

        browser = self._server.ServiceBrowserNew(avahi.IF_UNSPEC, avahi.PROTO_INET, service, '', 0)
        listener = dbus.Interface(bus.get_object(avahi.DBUS_NAME, browser), avahi.DBUS_INTERFACE_SERVICE_BROWSER)

        listener.connect_to_signal("ItemNew", self.item_new_handler)
        listener.connect_to_signal("ItemRemove", self.item_remove_handler)
        listener.connect_to_signal("AllForNow", self.all_for_now_handler)
        listener.connect_to_signal("CacheExhausted", self.cache_exhausted_handler)
        listener.connect_to_signal("Failure", self.failure_handler)

        self._mainloop = gobject.MainLoop()


    def service_resolved(self, *args):
        print 'New service: name = %s; address = %s; port = %s' % (args[2], args[7], args[8])


    def print_error(self, *args):
        print 'error_handler'
        print args[0]

    def item_new_handler(self, interface, protocol, name, stype, domain, flags):
        self._server.ResolveService(interface, protocol, name, stype, domain, avahi.PROTO_UNSPEC, dbus.UInt32(0), reply_handler=self.service_resolved, error_handler=self.print_error)


    def item_remove_handler(self, interface, protocol, name, stype, domain, flags):
        print "Removed service: %s" % name


    def all_for_now_handler(self):
        print "that's all for now"
        self._mainloop.quit()


    def cache_exhausted_handler(self):
        print "cache exhausted"


    def failure_handler(self, error):
        print "failure: %s" % error


    def browse(self):
        self._mainloop.run()


def browse_avahi(service):
    browser = ServiceBrowser(service)
    browser.browse()

def main():
    t0 = datetime.utcnow()
    print "browsing ..."
    browse_avahi('_http._tcp')
    print "done"
    print datetime.utcnow()-t0

if __name__ == '__main__':
    main()
于 2013-01-24T15:03:52.420 回答