我正在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始终为空,循环立即退出。
答案 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
在地址解析或不解析时捕获。