4

我正在尝试使用 NSNetService 在 iPhone 应用程序和 Mac 应用程序之间建立通信。

我已经设置了 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

这里不知道是connected还是not,can't find any connect method och connect state on sender.

所以我尝试使用以下命令写入输出流:

[self.connectedService getInputStream:&istream outputStream:&ostream];
NSString *test = @"test";
NSData *data = [test dataUsingEncoding:NSUTF8StringEncoding];
[ostream write:[data bytes] maxLength:[data length]];

并且还用 . 更新 TXTRecordData [sender setTXTRecordData:data];。我没有收到任何错误,我的 Mac 应用程序也没有任何反应。Mac 应用程序具有委托方法- (void)netService:(NSNetService *)sender didUpdateTXTRecordData:(NSData *)data

我不知道该怎么做。我想我遗漏了一些东西,但我不知道它是在 Mac 应用程序还是 iPhone 应用程序中。我想我首先需要以某种方式从 iPhone 应用程序连接到 Mac 应用程序,然后在 Mac 应用程序中添加一些监听连接的东西。

4

2 回答 2

4

不要相信苹果声称的一切,

使用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])
于 2013-01-27T14:15:44.890 回答
2

也许您需要先打开输出流?

[ostream open];
于 2012-08-24T09:34:34.100 回答