Cocoa Touch Bonjour如何处理NSNetService地址和uint8_t

时间:2011-07-17 00:03:01

标签: cocoa-touch cocoa http buffer bonjour

我正在尝试让iOS应用与使用Bonjour的服务器通信并使用HTTP命令。到目前为止,我已经能够找到本地域并找到我正在寻找的特定服务。我能够解析服务的地址,但我不知道如何从地址中获得有用的东西。 NSNetService的地址是一个NSData对象,我不知道如何处理它。我需要发送像GET和PUT这样的命令。什么可可类处理这样的事情?

我也试过从服务获取输入和输出流,但它们似乎是极低级别的流,我不知道如何正确处理缓冲区等等。

[service getInputStream:&inputStream outputStream:&outputStream]

NSOutputStream写入方法接受一个uint8_t缓冲区,我不知道如何创建。 NSInputStream读取方法返回一个uint8_t缓冲区,我不知道如何解释它。

我可以使用终端命令与此服务器通信。例如,向它发送命令LIST会导致它打印出我要查找的文件列表。如何在Cocoa中发送和获取这样的信息?

1 个答案:

答案 0 :(得分:3)

将数据写入输出流,因此将其发送到服务器:

NSString * stringToSend = @"Hello World!\n"; //The "\n" lets the receiving method described below function correctly. I don't know if you need it or not.
NSData * dataToSend = [stringToSend dataUsingEncoding:NSUTF8StringEncoding];
if (outputStream) {
    int remainingToWrite = [dataToSend length];
    void * marker = (void *)[dataToSend bytes];
    while (0 < remainingToWrite) {
        int actuallyWritten = 0;
        actuallyWritten = [outputStream write:marker maxLength:remainingToWrite];
        remainingToWrite -= actuallyWritten;
        marker += actuallyWritten;
    }
}

您可以发送此类数据,只需将其放入NSData对象。

要从服务器接收数据,请在输入流的NSStreamDelegate

中使用此代码
- (void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)streamEvent {
    NSInputStream * istream;
    NSOutputStream * ostream;
    switch(streamEvent) {
        case NSStreamEventHasBytesAvailable:;
            istream = (NSInputStream *)aStream;
            ostream = (NSOutputStream *)CFDictionaryGetValue(connections, istream);

            uint8_t buffer[2048];
            int actuallyRead = [istream read:(uint8_t *)buffer maxLength:2048];
            if (actuallyRead > 0) {
                NSData *data;
                data = [NSData dataWithBytes:buffer length:actuallyRead];
                NSString *string = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]autorelease];
                string = [string stringByReplacingOccurrencesOfString:@"\n" withString:@""];
                //Do something with the string...
            }
                break;
        case NSStreamEventEndEncountered:;
            istream = (NSInputStream *)aStream;
            ostream = nil;
            if (CFDictionaryGetValueIfPresent(connections, istream, (const void **)&ostream)) {
                [self shutdownInputStream:istream outputStream:ostream];
            }
                break;
        case NSStreamEventHasSpaceAvailable:
        case NSStreamEventErrorOccurred:
        case NSStreamEventOpenCompleted:
        case NSStreamEventNone:
        default:
            break;
    }
}

看看Apple's CocoaEcho Sample Code。它应该对你有帮助。