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