4

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

4

1 回答 1

11

其实你没有做错什么。

此事件(它是NSStreamEventHasSpaceAvailable)通常在写入流之后发生,告诉您流已准备好再次写入并且在打开可写流之后。请参阅NSStream 类参考,或者更准确地说:流事件常量

如果您不熟悉<<运算符,则意味着将位向左移动 n 个位置(每个移位等于乘以 2)。翻译将是:

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

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

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

于 2012-05-29T09:34:42.327 回答