繁体   English   中英

通过NSNetService连接并发送数据

[英]Connect to and send data via NSNetService

我正在尝试使用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

在这里,我不知道它是否已连接,在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 [sender setTXTRecordData:data]; 我没有任何错误,我的Mac App中没有任何反应。 Mac应用程序具有委托方法- (void)netService:(NSNetService *)sender didUpdateTXTRecordData:(NSData *)data

我不知道该如何进行。 我想我丢失了一些东西,但是我不知道它在Mac应用程序还是iPhone应用程序中。 我想我首先需要以某种方式从iPhone应用程序连接到Mac应用程序,然后在Mac应用程序中添加一些监听连接的内容。

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

使用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])

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

[ostream open];

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM