1

目标是在使用 dns_sd API 成功解析服务后获取读/写流。我从 Apple 的 DNSSDObjects 示例项目开始,我正在编辑 DNSSDService.m 文件以在服务解决后获取读取和写入流。

这是我到目前为止所得到的。似乎它应该工作,但它没有:(

通过遵循此线程上的代码,我已经走到了这一步,尽管我不完全确定这应该是如何完成的。

编辑:Apple 的文档在这里确认应该这样做......“所以,一旦你使用 DNSServiceResolve 解析了服务,你应该将服务的 DNS 名称(你的 DNSServiceResolveReply 回调的 hosttarget 参数)传递给连接 -按名称 API(如 CFStreamCreatePairWithSocketToHost)。”

// Called by DNS-SD when something happens with the resolve operation.
static void ResolveReplyCallback(
    DNSServiceRef           sdRef,
    DNSServiceFlags         flags,
    uint32_t                interfaceIndex,
    DNSServiceErrorType     errorCode,
    const char *            fullname,
    const char *            hosttarget,
    uint16_t                port,
    uint16_t                txtLen,
    const unsigned char *   txtRecord,
    void *                  context
) 
{
  CFStringRef host = CFStringCreateWithCString(kCFAllocatorDefault,
                                               hosttarget, 
                                               kCFStringEncodingUTF8);  
    DNSSDService *       obj;
    #pragma unused(interfaceIndex)

    assert([NSThread isMainThread]);  // b/c sdRef dispatches to the main queue

    obj = (__bridge DNSSDService *) context;
    assert([obj isKindOfClass:[DNSSDService class]]);
    assert(sdRef == obj->sdRef_);
    #pragma unused(sdRef)
    #pragma unused(flags)
    #pragma unused(fullname)
    #pragma unused(txtLen)
    #pragma unused(txtRecord)

    if (errorCode == kDNSServiceErr_NoError) {
        [obj resolveReplyWithTarget:[NSString stringWithUTF8String:hosttarget] 
                               port:ntohs(port)];
    } else {
      [obj stopWithError:[NSError errorWithDomain:NSNetServicesErrorDomain
                                             code:errorCode
                                         userInfo:nil]
                  notify:YES];
    }

//now let's get read&write streams?
  CFReadStreamRef   readStream = NULL;
  CFWriteStreamRef  writeStream = NULL;
  CFStreamCreatePairWithSocketToHost(kCFAllocatorDefault,
                                     host,
                                     port,
                                     &readStream,
                                     &writeStream
                                     );
  if (readStream && writeStream) {
    CFReadStreamSetProperty(readStream,
                            kCFStreamPropertyShouldCloseNativeSocket, 
                            kCFBooleanTrue);
    CFWriteStreamSetProperty(writeStream,
                            kCFStreamPropertyShouldCloseNativeSocket, 
                            kCFBooleanTrue);

    obj.inputStream =  (__bridge_transfer  NSInputStream *) readStream;
    obj.outputStream = (__bridge_transfer NSOutputStream *) writeStream;

  }
  CFRelease(host);
}
4

0 回答 0