Bonjour 服务发现找不到主机

Bonjour service discovery not finding hosts

我正在尝试在 Swift3 中实施 Bonjour NetServiceBrowser,以便发现我网络上的主机。

当我使用以下命令在终端中手动搜索时,我会找到主机。

dns-sd -B

然而,当我尝试在 Swift 中使用 NetServiceBrowser(见下面的代码)时,它只会打印 "starting search.."。我通过遵循 Bonjour documentation.

实现了这个 class

我不明白哪里出了问题。 Bonjour 在 Swift 上的工作方式是否不同?我在网上找不到有效的例子。我在 domain ("local", "local.", "") 或 name.

上尝试了几种变体
class ZeroConf: NSObject, NetServiceBrowserDelegate, NetServiceDelegate{

    var browser: NetServiceBrowser!
    var services = [NetService]()
    let domain = "local"
    let name = "_http._tcp"



    func startSearch(){
        self.services.removeAll()
        self.browser = NetServiceBrowser()
        self.browser.delegate = self
        self.browser.searchForServices(ofType: name, inDomain: domain)
    }


    func netService(_ sender: NetService, didNotPublish errorDict: [String : NSNumber]) {
        debugPrint(errorDict)
    }

    func netServiceBrowserWillSearch(_ browser: NetServiceBrowser) {
        print("starting search..")
    }

    func netServiceBrowserDidStopSearch(_ browser: NetServiceBrowser) {
        print("Stoped search")
    }

    func netServiceBrowser(_ browser: NetServiceBrowser, didNotSearch errorDict: [String : NSNumber]) {
        print("error in search")
        debugPrint(errorDict)
    }

    func netServiceBrowser(_ browser: NetServiceBrowser, didFind service: NetService, moreComing: Bool) {
        print("found service")
        services.append(service)
        debugPrint(service)
    }

    func netServiceBrowser(_ browser: NetServiceBrowser, didRemove service: NetService, moreComing: Bool) {
        if let ix = self.services.index(of:service) {
            self.services.remove(at:ix)
            print("removing a service")
        }
    }

    func netServiceDidResolveAddress(_ sender: NetService) {
        print("did resolve address")
    }
}

我发现了为什么它对我不起作用。我试图从主循环执行代码,而它显然应该从不同的线程调用。因此,我将 startSearch 中的代码更改为

DispatchQueue.main.async {
        self.browser.schedule(in: RunLoop.current, forMode: .defaultRunLoopMode)
        self.browser.searchForServices(ofType: self.name, inDomain: self.domain)
        RunLoop.current.run()
}