Bonjour
- 官方链接
NetService
- 一种使用多播DNS广播其可用性的网络服务
NetServiceBrowser
- 一种使用多播DNS查找网络上发布的服务的网络服务浏览器
应用
该技术目前我们公司,是用于发现通局域网中的设备。然后通过socket 去实现投屏、和手机遥控的功能
NetService 详解
- 初始化的两种方式
- (instancetype)initWithDomain:(NSString *)domain
type:(NSString *)type
name:(NSString *)name;
- (instancetype)initWithDomain:(NSString *)domain
type:(NSString *)type
name:(NSString *)name
port:(int)port;
字段分析:
- domain:
服务的域。要解析默认域,传入一个空字符串(@"")。如果要将解析限制在本地域,请使用@"local."。
如果您正在创建此对象来解析您的应用程序之前存储的信息的服务,您应该将此设置为最初发现该服务的域。
您也可以使用NSNetServiceBrowser对象来获取一个可能的域列表,您可以在其中发现和解析服务。
- type:
类型必须同时包含服务类型和传输层信息。为了确保mDNS响应器搜索服务,而不是主机,在服务名称和传输层名称前面加上一个下划线字符(“_”)。例如,要在TCP上搜索HTTP服务,可以使用字符串“_http._tcp.”。请注意,字符串末尾的句点字符是必需的,它表明域名是绝对名称。
- name:
要解析的服务的名称
var service:NetService?
let port:Int32 = 6689
let type:String = "_db_controller123._tcp"
service = NetService(domain: "local.", type: type, name: "riverliBonjour", port: port)
if service == nil {
print("服务启动失败")
return
}
service?.delegate = self
主要区别是有无端口,不指定端口的话,他们的发布方式不同
- 发布服务
//指定端口的发布方式
service?.publish()
//这种方式会主动的分配一个端口(指定了端口不生效)
service?.publish(options: .listenForConnections)
- NetServiceDelegate
//将要发布
optional func netServiceWillPublish(_ sender: NetService)
//发布成功
optional func netServiceDidPublish(_ sender: NetService)
//发布失败
optional func netService(_ sender: NetService, didNotPublish errorDict: [String : NSNumber])
//拿到解析结果
func netServiceDidResolveAddress(_ sender: NetService)
//解析出错
func netService(_ sender: NetService, didNotResolve errorDict: [String : NSNumber])
//服务停止
func netServiceDidStop(_ sender: NetService)
//给定服务的TXT记录已经更新
func netService(_ sender: NetService, didUpdateTXTRecord data: Data)
//当客户端连接到由Bonjour管理的服务时调用
func netService(_ sender: NetService, didAcceptConnectionWith inputStream: InputStream, outputStream: OutputStream)
服务端的总体代码
import UIKit
class YMServiceHomeVC: UIViewController {
var service:NetService?
let port:Int32 = 6688
let type:String = "_db_controller123._tcp."
override func viewDidLoad() {
super.viewDidLoad()
title = "服务端"
publish()
}
@IBAction func startSocket(_ sender: Any) {
let vc = YMServiceMsgBoardVC()
vc.port = Int(port)
navigationController?.pushViewController(vc, animated: true)
}
//发布服务
func publish(){
service = NetService(domain: "local.", type: type, name: "riverliBonjour", port: port)
if service == nil {
print("服务启动失败")
return
}
service?.delegate = self
//传递额外的数据
let data = NetService.data(fromTXTRecord:["Allenzhan":("Allen".data(using: .utf8))!])
let status = service?.setTXTRecord(data)
if status == true {
print("设置TXT 文案成功")
}else{
print("设置TXT 文案失败")
}
service?.publish()
//这种方式会主动的分配一个端口
// service?.publish(options: .listenForConnections)
// service?.resolve(withTimeout: 0.0)
}
}
extension YMServiceHomeVC: NetServiceDelegate{
func netServiceWillPublish(_ sender: NetService) {
print("将要发布")
}
func netServiceDidPublish(_ sender: NetService) {
print("发布成功")
}
}
客户端
NetServiceBrowser
info.plist 配置
- 初始化
let port:Int32 = 1234
let type:String = "_db_controller123._tcp"
var seviceBrowser:NetServiceBrowser?
func createClient() {
seviceBrowser = NetServiceBrowser.init()
seviceBrowser?.delegate = self
//加入runloop 如果在子线程的话
// seviceBrowser?.schedule(in: RunLoop.current, forMode: .common)
seviceBrowser?.searchForServices(ofType: type, inDomain: "local.")
}
- 代理NetServiceBrowserDelegate
func netServiceBrowserWillSearch(_ browser: NetServiceBrowser){
print("开始搜索")
}
func netServiceBrowserDidStopSearch(_ browser: NetServiceBrowser){
print("结束搜索")
}
func netServiceBrowser(_ browser: NetServiceBrowser, didNotSearch errorDict: [String : NSNumber]){
print("没有搜索到: error", errorDict)
}
func netServiceBrowser(_ browser: NetServiceBrowser, didFindDomain domainString: String, moreComing: Bool){
print("搜索到 Domain:" + domainString + "-- morecoming:" ,moreComing)
}
func netServiceBrowser(_ browser: NetServiceBrowser, didFind service: NetService, moreComing: Bool){
print("搜索到 service:" , service , "-- morecoming:" ,moreComing)
services.append(service)
//这里要给sevice 设置代理以便监听数据的解析
service.delegate = self
//这里要设置解析超时时间 0 的话是永久。这里服务端也可以发布成功后设置,但是客户端最好自己设置一下,不然怕不能解析到数据
service.resolve(withTimeout: 5)
}
func netServiceBrowser(_ browser: NetServiceBrowser, didRemoveDomain domainString: String, moreComing: Bool){
print("删除 Domain:" + domainString + "-- morecoming:" ,moreComing)
}
func netServiceBrowser(_ browser: NetServiceBrowser, didRemove service: NetService, moreComing: Bool){
print("删除 service:" , service , "-- morecoming:" ,moreComing)
}
- NetServiceDelegate
func netServiceDidResolveAddress(_ sender: NetService){
print("----------")
print(sender)
if let ipAddresses = sender.addresses {
//获取记录的数据(服务端用来传递我们需要的数据)
let data = sender.txtRecordData()
let dict = NetService.dictionary(fromTXTRecord: data!)
print(dict)
for ipData in ipAddresses {
//解析ip
let ipStr = IPFrom(data: ipData);
print("ipstr = " + ipStr)
if ipStr.count > 0 {
dataSource.append((ipStr,sender.port))
tableView.reloadData()
}
}
}
print(sender.domain)
print(sender.hostName)
print(sender.name)
print(sender.port)
print("----------")
}
- 客户端所有代码
import UIKit
class YMClientHomeVC: UIViewController {
@IBOutlet weak var tableView: UITableView!
let port:Int32 = 1234
let type:String = "_db_controller123._tcp"
var services:[NetService] = [NetService]()
var seviceBrowser:NetServiceBrowser?
var dataSource:[(String,Int)] = [(String,Int)]()
override func viewDidLoad() {
super.viewDidLoad()
title = "客户端"
createClient()
}
func createClient() {
seviceBrowser = NetServiceBrowser.init()
seviceBrowser?.delegate = self
// seviceBrowser?.schedule(in: RunLoop.current, forMode: .common)
seviceBrowser?.searchForServices(ofType: type, inDomain: "local.")
}
}
extension YMClientHomeVC:NetServiceBrowserDelegate{
func netServiceBrowserWillSearch(_ browser: NetServiceBrowser){
print("开始搜索")
}
func netServiceBrowserDidStopSearch(_ browser: NetServiceBrowser){
print("结束搜索")
}
func netServiceBrowser(_ browser: NetServiceBrowser, didNotSearch errorDict: [String : NSNumber]){
print("没有搜索到: error", errorDict)
}
func netServiceBrowser(_ browser: NetServiceBrowser, didFindDomain domainString: String, moreComing: Bool){
print("搜索到 Domain:" + domainString + "-- morecoming:" ,moreComing)
}
func netServiceBrowser(_ browser: NetServiceBrowser, didFind service: NetService, moreComing: Bool){
print("搜索到 service:" , service , "-- morecoming:" ,moreComing)
services.append(service)
service.delegate = self
service.resolve(withTimeout: 5)
}
func netServiceBrowser(_ browser: NetServiceBrowser, didRemoveDomain domainString: String, moreComing: Bool){
print("删除 Domain:" + domainString + "-- morecoming:" ,moreComing)
}
func netServiceBrowser(_ browser: NetServiceBrowser, didRemove service: NetService, moreComing: Bool){
print("删除 service:" , service , "-- morecoming:" ,moreComing)
}
}
extension YMClientHomeVC: NetServiceDelegate {
func netServiceDidResolveAddress(_ sender: NetService){
print("----------")
print(sender)
if let ipAddresses = sender.addresses {
let data = sender.txtRecordData()
let dict = NetService.dictionary(fromTXTRecord: data!)
print(dict)
for ipData in ipAddresses {
let ipStr = IPFrom(data: ipData);
print("ipstr = " + ipStr)
if ipStr.count > 0 {
dataSource.append((ipStr,sender.port))
tableView.reloadData()
}
}
}
print(sender.domain)
print(sender.hostName)
print(sender.name)
print(sender.port)
print("----------")
}
func netService(_ sender: NetService, didNotResolve errorDict: [String : NSNumber]) {
print("--------netService didNotResolve:", errorDict, "--------")
}
func netServiceDidStop(_ sender: NetService) {
print("--------netServiceDidStop", "--------")
}
func netService(_ sender: NetService, didUpdateTXTRecord data: Data) {
print("--------netService didUpdateTXTRecord", "--------")
}
func netService(_ sender: NetService, didAcceptConnectionWith inputStream: InputStream, outputStream: OutputStream) {
print("--------netService didAcceptConnectionWith", "--------")
}
// MARK: util 获取ip地址
func IPFrom(data: Data) -> String {
let dataIn: NSData = data as NSData
var storage = sockaddr_storage()
dataIn.getBytes(&storage, length: MemoryLayout.size)
if Int32(storage.ss_family) == AF_INET {
let addr4 = withUnsafePointer(to: &storage) {
$0.withMemoryRebound(to: sockaddr_in.self, capacity: 1) {
$0.pointee
}
}
let ipString = String(cString: inet_ntoa(addr4.sin_addr), encoding: .ascii) ?? ""
return ipString
}
return ""
}
}
extension YMClientHomeVC:UITableViewDelegate,UITableViewDataSource{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataSource.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell.init(style: .default, reuseIdentifier: "reuseID")
cell.textLabel?.text = dataSource[indexPath.row].0 + ":" + "\(dataSource[indexPath.row].1)"
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let vc = YMClientMsgBoardVC()
vc.ipStr = dataSource[indexPath.row].0
vc.port = dataSource[indexPath.row].1
navigationController?.pushViewController(vc, animated: true)
}
}
关于mDNS 可以参考mDNS