iOS Bonjour 本地服务通信

2020-01-05  本文已影响0人  风儿吹啊吹

Bonjour 是什么?

bonjour其实来自法语,是你好的意思。而Bonjour服务是苹果公司发布的一个基于ZEROCONF工作组(IETF下属小组)的工作,用于实现零配置网络联网的解决方案。Bonjour是基于IP层协议的,简单来说,就是一套解决方案,能够不需要复杂的配置,即可互相发现彼此的解决方案。可以用它来轻松探测并连接到相同网络中的其他设备,并与别的智能硬件进行交互或者其他操作。典型的Bonjour应用有Remote、AirPrint等。(本段摘自Bonjour的使用-本地通信/智能交互)

如何实现

    属性申明 定义
    let domain: String = "local."
    let type: String = "_xiaopao._tcp"
    let port:Int32 = 1234
    var service: NetService!
    var browser: NetServiceBrowser!

1、发布服务

    @objc func publishService() {
        // 发布服务
        let name: String = "\(Int(Date().timeIntervalSince1970 * 1000))"
        service = NetService(domain: domain, type: type, name: name, port: port)
        service.delegate = self
        service.schedule(in: RunLoop.current, forMode: .common)
        
        // 发布的数据
        let dict: [String: Data] = ["name": "xiaopao".data(using: .utf8) ?? Data()]
        let data = NetService.data(fromTXTRecord: dict)
        service.setTXTRecord(data)
        
        // 开始发布
        service.publish()
    }
1.1 发布服务代理
extension ViewController: NetServiceDelegate {
    // 将要发布服务
    func netServiceWillPublish(_ sender: NetService) {
        print(#function)
    }
    
    // 发布失败处理
    func netService(_ sender: NetService, didNotPublish errorDict: [String : NSNumber]) {
        print(#function)
    }
    
    // 发布服务完成
    func netServiceDidPublish(_ sender: NetService) {
        print(#function)
    }
}

2、浏览服务

    @objc func browseService() {
        //浏览服务
        browser = NetServiceBrowser()
        browser.delegate = self
        browser.schedule(in: RunLoop.current, forMode: .common)
        browser.searchForServices(ofType: type, inDomain: domain)
    }
2.1浏览服务代理
// 浏览服务代理
extension ViewController: NetServiceBrowserDelegate {
    // 将要搜索服务
    func netServiceBrowserWillSearch(_ browser: NetServiceBrowser) {
        print(#function)
    }
    
    // 搜索不成功处理
    func netServiceBrowser(_ browser: NetServiceBrowser, didNotSearch errorDict: [String : NSNumber]) {
        print(#function)
    }
    
    // 搜索到服务
    func netServiceBrowser(_ browser: NetServiceBrowser, didFind service: NetService, moreComing: Bool) {
        print(#function)
        
        // 搜索服务开始处理
        //调用 NetServiceDelegate代理的 netServiceWillResolve、netServiceDidResolveAddress等方法
        self.service = service
        service.delegate = self
        service.schedule(in: RunLoop.current, forMode: .common)
        service.resolve(withTimeout: 5)
        
    }
    
    // 服务已消失或者不可用
    func netServiceBrowser(_ browser: NetServiceBrowser, didRemove service: NetService, moreComing: Bool) {
        print(#function)
        let name = service.name
        let type = service.type
        let domain = service.domain
        print("移除服务:····name:\(name),type:\(type),domain:\(domain)")
    }
}

3、互相通信

// 发布服务代理
extension ViewController: NetServiceDelegate {
    // 将要处理服务
    func netServiceWillResolve(_ sender: NetService) {
        print(#function)
    }
    
    // 处理服务
    func netServiceDidResolveAddress(_ sender: NetService) {
        guard let txtData = sender.txtRecordData() else { return }
        
        print(#function)
        let name = sender.name
        let type = sender.type
        let domain = sender.domain
        let dict = resolveDictionary(fromTXTRecord: txtData)
        print("处理服务:····name:\(name),type:\(type),domain:\(domain),data\(dict)")
    }
    
    // 处理data数据转成 字典[String:String]
    func resolveDictionary(fromTXTRecord data: Data) -> [String: String] {
        var dict = [String: String]()
        var offset = 0
        
        data.withUnsafeBytes({
            while offset < $0.count {
                let recordLength = Int($0[offset])
                offset += 1
                if recordLength > 0 {
                    let subBytes = $0[offset..<offset + recordLength]
                    let compoments = subBytes.split(separator: 61)
                    if compoments.count == 2 {
                        let key = String(bytes: Data(compoments[0]), encoding: .utf8) ?? ""
                        let value = String(bytes: Data(compoments[1]), encoding: .utf8) ?? ""
                        dict[key] = value
                    }
                }
                offset += recordLength
            }
        })
        return dict
    }
    
    // 处理服务时 发生错误
    func netService(_ sender: NetService, didNotResolve errorDict: [String : NSNumber]) {
        print(#function)
    }
    
    func netService(_ sender: NetService, didUpdateTXTRecord data: Data) {
        print(#function)
    }
}

参考文档:
https://www.jianshu.com/p/94c5848894e1

上一篇下一篇

猜你喜欢

热点阅读