我正在尝试使用NSNetService在iPhone应用程序和Mac应用程序之间设置upp通信。
到目前为止,我已经将Mac应用程序设置为发布iPhone应用程序可以发现的NSNetService,但我不知道如何在它们之间发送数据。
在我的Mac应用程序中,我使用以下命令发布我的NSNetService:
self.netService = [[NSNetService alloc] initWithDomain:@"" type:@"_sputnik._tcp" name:@"" port:port];
if (self.netService) {
[self.netService scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:@"PrivateMyMacServiceMode"];
[self.netService setDelegate:self];
[self.netService publish];
[self.netService startMonitoring];
NSLog(@"SUCCESS!");
} else {
NSLog(@"FAIL!");
}一切看起来都很好,委托方法- (void)netServiceDidPublish:(NSNetService *)sender (在Mac应用程序中)被触发。
在iPhone应用程序中,我创建了NSNetServiceBrowser的一个实例,一两秒钟后,它会触发didFindService委托方法。
- (void)netServiceBrowser:(NSNetServiceBrowser *)aNetServiceBrowser didFindService:(NSNetService *)aNetService moreComing:(BOOL)moreComing {
TRACE;
NSLog(@"moreComing: %d", moreComing);
self.connectedService = aNetService;
if (!moreComing) {
self.connectedService.delegate = self;
[self.connectedService resolveWithTimeout:30];
}
}在此之后,它直接触发下一个委托方法- (void)netServiceDidResolveAddress:(NSNetService *)sender。
在这里我不知道它是连接的还是不连接的,在sender上找不到任何连接状态的连接方法。
因此,我尝试使用以下命令写入输出流:
[self.connectedService getInputStream:&istream outputStream:&ostream];
NSString *test = @"test";
NSData *data = [test dataUsingEncoding:NSUTF8StringEncoding];
[ostream write:[data bytes] maxLength:[data length]];并使用[sender setTXTRecordData:data];更新TXTRecordData。我没有收到任何错误,并且在我的Mac应用程序中没有任何反应。Mac应用程序有一个委托方法- (void)netService:(NSNetService *)sender didUpdateTXTRecordData:(NSData *)data。
我不知道该怎么做。我想我漏掉了什么,但我不知道它是在Mac应用程序中还是在iPhone应用程序中。我猜我首先需要以某种方式从iPhone应用程序连接到Mac应用程序,然后在Mac应用程序中添加一些侦听连接的东西。
发布于 2013-01-27 22:15:45
不要相信苹果所说的一切,
使用NSNetworkService设置流有很多问题。
如果您执行以下操作,它将会工作:
首先获取要在其上发布网络的端口。不要自己选择端口。
然后,您可以使用该端口发布网络。
使用以下命令获取客户端流:
[nService qNetworkAdditions_getInputStream:&istream outputStream:&ostream];许多程序员犯的错误是通过自己选择一个端口来发布网络,然后用
[nService qNetworkAdditions_getInputStream:&istream outputStream:&ostream];流无法打开...
结论:首先获取端口,然后使用如下内容进行发布:
self.netService = [[NSNetService alloc] initWithDomain:@"local" type:@"_xxx._tcp." name:serviceName port:(int) self.port];
open streams with
CFStreamCreatePairWithSocket(kCFAllocatorDefault, nativeSocketHandle, &readStream, &writeStream);
open streams with (you open a connection here)
EchoConnection * connection = [[EchoConnection alloc] initWithInputStream:( NSInputStream *)readStream outputStream:( NSOutputStream *)writeStream];
[self.connections addObject:connection];然后浏览并添加服务
然后在您浏览的服务中打开所需服务的流
[nService qNetworkAdditions_getInputStream:&istream outputStream:&ostream];
(and open them with [istream open] and [ostream open])发布于 2012-08-24 17:34:34
也许你需要先打开输出流?
[ostream open];https://stackoverflow.com/questions/12055916
复制相似问题