正在關注this example我想在獲取所有元素並將其返回列表中時停止該服務。停止Avahi服務並返回元素列表
要停止無限循環,請致電gobject.MainLoop().quit()
,但不知道何時何地致電。 謝謝
正在關注this example我想在獲取所有元素並將其返回列表中時停止該服務。停止Avahi服務並返回元素列表
要停止無限循環,請致電gobject.MainLoop().quit()
,但不知道何時何地致電。 謝謝
你會想要停止服務瀏覽現在最後的服務已經到達。這將爲您提供當前可用服務的快照。
C層有一個標誌讓你可以檢查更多的服務是否即將到來。它被稱爲AVAHI_BROWSER_ALL_FOR_NOW
。我對python綁定不熟悉,但也許可以在回調的stype
或flags
參數中以某種方式檢查此標誌嗎?
當你看到此標誌設置 - 通話gobject.MainLoop().quit()
你要聽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()