gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 16:31:09 26 4
gpt4 key购买 nike

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

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

[service getInputStream:&inputStream outputStream:&outputStream]

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

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

最佳答案

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

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 .它应该对您有所帮助。

关于cocoa-touch - Cocoa Touch Bonjour如何处理NSNetService地址和uint8_t,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6721068/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com