NSNetService不包含任何地址

时间:2019-03-23 19:33:09

标签: ios objective-c macos bonjour nsnetservice

我正在Mac应用程序中托管服务,并与iOS应用程序连接。虽然iOS应用可以找到该服务,但该服务不包含任何地址,因此我无法连接套接字。

这是我在Mac上的托管代码:

- (void)start {

    queue = dispatch_queue_create("KeyboardServer", DISPATCH_QUEUE_CONCURRENT);

    socket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:queue];

    NSError *error = nil;

    if ([socket acceptOnPort:0 error:&error]) {

        service = [[NSNetService alloc] initWithDomain:@"local." type:@"_probonjore._tcp." name:@"TestServer" port:[socket localPort]];

        service.delegate = self;

        [service publish];

    } else {
        NSLog(@"Unable to create server");
    }
}

这是iOS上的连接代码:

- (BOOL)connectToServer:(NSNetService *)service {

    NSArray *addresses = service.addresses;

    socket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:queue];

    for (NSData *address in addresses) {

        NSError *error;

        if ([socket connectToAddress:address error:&error]) {
            NSLog(@"Socket connected!");

            return true;
        }
    }

    return false;
}

问题在于,service.addresses始终为空,循环立即退出。

1 个答案:

答案 0 :(得分:0)

对于任何好奇的人,我四处搜寻并找到了解决方案。

- (void)netServiceBrowser:(NSNetServiceBrowser *)browser didFindService:(NSNetService *)service moreComing:(BOOL)moreComing

功能,您需要:

  • 将服务添加到数组以在对象超出范围时立即停止释放对象
  • 在对象上设置委托,以便您可以响应其地址解析
  • 调用函数使其解析

看起来像这样:

- (void)netServiceBrowser:(NSNetServiceBrowser *)browser didFindService:(NSNetService *)service moreComing:(BOOL)moreComing {

    NSLog(@"Found Service %@", [service name]);

    [services addObject:service];

    [service setDelegate:self];

    [service resolveWithTimeout:5.0f];
}

您然后要实现

- (void)netService:(NSNetService *)sender didNotResolve:(NSDictionary *)errorDict

- (void)netServiceDidResolveAddress:(NSNetService *)service

在地址解析或不解析时捕获。