gpt4 book ai didi

objective-c - NSStream 处理事件给出状态 4

转载 作者:可可西里 更新时间:2023-11-01 02:33:19 24 4
gpt4 key购买 nike

我正在尝试使用 TCP 连接应用程序,并且在 handleEvent 上收到 NSStreamEvent“4”。我究竟做错了什么?

我的代码是这样的

-(void) initNetworkCommunication {

CFReadStreamRef readStream;
CFWriteStreamRef writeStream;
CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)@"localhost", 80, &readStream, &writeStream);

inputStream = (__bridge_transfer NSInputStream *)readStream;
outputStream = (__bridge_transfer NSOutputStream *)writeStream;
[inputStream setDelegate:self];
[outputStream setDelegate:self];
[inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[inputStream open];
[outputStream open];

}


- (IBAction)didTapButton:(id)sender {

NSString *response = inputTextField.text;
NSLog(@"%@", response);
NSData *data = [[NSData alloc] initWithData:[response dataUsingEncoding:NSASCIIStringEncoding]];
[outputStream write:[data bytes] maxLength:[data length]];
}



- (void)stream:(NSStream *)theStream handleEvent:(NSStreamEvent)streamEvent {

switch (streamEvent) {

case NSStreamEventOpenCompleted:
NSLog(@"Stream opened");
break;

case NSStreamEventHasBytesAvailable:
NSLog(@"Stream has bytes available");

break;

case NSStreamEventErrorOccurred:
NSLog(@"Can not connect to the host!");
break;

case NSStreamEventEndEncountered:
NSLog(@"Stream closed");

break;

default:

NSLog(@"Unknown event: %@ : %d", theStream, streamEvent);
}

}

控制台给出,

2012-05-29 13:37:07.132 GestureTrial[24289:f803] Stream opened
2012-05-29 13:37:07.133 GestureTrial[24289:f803] Stream opened
2012-05-29 13:37:07.133 GestureTrial[24289:f803] Unknown event: <__NSCFOutputStream: 0x6b85c70> : 4

当试图向服务器发送消息时。我用 Mac 的 tcp 测试器应用程序试过了,它工作正常,所以可能不是防火墙问题。设备和模拟器的输出相同。任何帮助将非常感激。

最佳答案

其实你并没有做错什么。

此事件(它是 NSStreamEventHasSpaceAvailable )通常发生在写入流之后,告诉您流已准备好再次写入,并且发生在打开可写流之后。请引用NSStream Class Reference或者,准确地说:Stream Event Constants .

如果您不熟悉 <<运算符,表示向左移位n位(每次移位等于乘以2)。翻译将是:

typedef enum {
NSStreamEventNone = 0,
NSStreamEventOpenCompleted = 1,
NSStreamEventHasBytesAvailable = 2,
NSStreamEventHasSpaceAvailable = 4,
NSStreamEventErrorOccurred = 8,
NSStreamEventEndEncountered = 16
};

在许多应用程序中,您会看到此事件被简单地忽略(未处理),因为它通常在写入流后很快发生。如果出现问题,您会得到 NSStreamEventErrorOccurredNSStreamEventEndEncountered这些是你需要处理的。你可以使用 NSStreamEventHasSpaceAvailable作为一个标志,它是好的。发送更多数据。

您还应该知道两个流(inputStream 和 outputStream)都在调用相同的委托(delegate)方法。这就是为什么你得到两个 NSStreamEventOpenCompleted事件开始。但在许多情况下,这应该不是问题。如果需要,您始终可以检查哪个流是事件的发起者。

关于objective-c - NSStream 处理事件给出状态 4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10795344/

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