You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift 3中Bonjour NetService的TXT记录设置与读取方法咨询

我来帮你搞定Bonjour TXT记录的问题!在Swift 3里处理NetService的TXT记录其实没那么复杂,我给你整理了设置和读取的完整实现步骤:

设置NetService的TXT记录

首先,Bonjour的TXT记录要求遵循RFC 6763规范:每个键值对以1字节的长度值开头,后面跟着key=value格式的字符串,多个键值对直接拼接(长度字节会自动区分每个条目)。

我们可以先写一个工具函数,把包含user_id和name的字典转换成符合要求的Data:

func txtRecordData(from dictionary: [String: String]) -> Data? {
    var data = Data()
    for (key, value) in dictionary {
        guard let entry = "\(key)=\(value)".data(using: .utf8) else {
            continue
        }
        // 每个条目总长度不能超过255字节(符合Bonjour规范)
        guard entry.count <= 255 else {
            print("TXT条目 \(key)=\(value) 过长,超出255字节限制")
            continue
        }
        // 先添加条目长度,再添加条目内容
        data.append(UInt8(entry.count))
        data.append(entry)
    }
    return data.isEmpty ? nil : data
}

然后在发布NetService之后,调用setTXTRecord(_:)方法传入转换后的Data即可:

// 假设你已经创建并发布了NetService实例
let chatService = NetService(domain: "", type: "_chat-service._tcp.", name: "我的聊天服务", port: 54321)
chatService.publish()

// 准备要添加的TXT记录参数
let userInfo = [
    "user_id": "1001",
    "name": "Rajat Jain"
]

if let txtData = txtRecordData(from: userInfo) {
    chatService.setTXTRecord(txtData)
}
读取NetService的TXT记录

当发现其他设备的NetService时,可以通过txTRecordData()获取TXT记录的Data,再转换成字典方便使用。同样写一个解析函数:

func dictionary(fromTXTRecordData data: Data?) -> [String: String]? {
    guard let data = data else { return nil }
    var userDict = [String: String]()
    var currentIndex = data.startIndex
    
    while currentIndex < data.endIndex {
        // 读取当前条目的长度
        let entryLength = Int(data[currentIndex])
        currentIndex = data.index(currentIndex, offsetBy: 1)
        
        // 读取对应长度的条目内容
        guard let entryEndIndex = data.index(currentIndex, offsetBy: entryLength, limitedBy: data.endIndex) else {
            break
        }
        let entryData = data[currentIndex..<entryEndIndex]
        guard let entryString = String(data: entryData, encoding: .utf8) else {
            currentIndex = entryEndIndex
            continue
        }
        
        // 拆分key和value
        if let equalsPos = entryString.range(of: "=") {
            let key = String(entryString[..<equalsPos.lowerBound])
            let value = String(entryString[equalsPos.upperBound...])
            userDict[key] = value
        }
        
        currentIndex = entryEndIndex
    }
    return userDict
}

使用时,比如在NetService的回调方法里读取:

func netServiceDidResolveAddress(_ sender: NetService) {
    if let userInfo = dictionary(fromTXTRecordData: sender.txTRecordData()) {
        let userId = userInfo["user_id"] ?? "未知ID"
        let userName = userInfo["name"] ?? "未知姓名"
        print("发现聊天用户:\(userName)(ID:\(userId))")
    }
}

几个注意点:

  • 每个TXT条目(包括key=value)的总长度不能超过255字节,避免内容过长
  • 统一使用UTF-8编码,保证跨设备的兼容性
  • 建议在NetService发布成功后再设置TXT记录,确保其他设备能获取到完整信息

内容的提问来源于stack exchange,提问作者Rajat Jain

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 08:33:02