NSStream处理事件给予状态4

时间:2012-05-29 08:09:45

标签: objective-c ios tcp nsstream

我正在尝试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测试器应用程序,它运行正常,因此可能不是防火墙问题。设备和模拟器的输出相同。任何帮助将非常感激。

1 个答案:

答案 0 :(得分:9)

其实你没有做错任何事。

此事件(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作为标志,它是o.k.发送更多数据。

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