关注this example我想在获取所有元素并在列表中返回时停止服务。
要停止无限循环,请调用gobject.MainLoop().quit()
,但不知道何时或何处调用。
感谢
答案 0 :(得分:2)
当现在的最后一个服务到达时,您将要停止服务浏览。这将为您提供当前可用服务的快照。
C层中有一个标志,允许您检查是否有更多服务即将到来。它被称为AVAHI_BROWSER_ALL_FOR_NOW
。我不熟悉 python 绑定,但也许这个标志可以在回调的stype
或flags
参数中以某种方式进行检查?
当您看到此标志设置时 - 请致电gobject.MainLoop().quit()
答案 1 :(得分:1)
您也想要收听 AllForNow 信号。考虑 CacheExhausted 和失败。 org.freedesktop.Avahi.ServiceBrowser 的界面声明为here。
在我的机器上运行以下命令会在大约一秒后返回并打印:
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()