我正在从本教程中学习 iOS 网络编程。我尝试修改代码,以便在连接成功后立即向服务器发送响应。我更改的代码的唯一部分是在这个函数中。问题是应用程序停止并且行上没有任何反应[outputStream write:[data bytes] maxLength:[data length]];
因此NSLog(@"sent test");
没有被执行。我究竟做错了什么?
- (void)stream:(NSStream *)theStream handleEvent:(NSStreamEvent)streamEvent {
NSLog(@"stream event %i", streamEvent);
switch (streamEvent) {
case NSStreamEventOpenCompleted:
NSLog(@"Stream opened");
//my code
if (theStream == outputStream) {
NSLog(@"outputStream");
NSData* data = [NSData dataWithBytes:@"test" length:4];
[outputStream write:[data bytes] maxLength:[data length]];
NSLog(@"sent test");
} //end my code
break;
case NSStreamEventHasBytesAvailable:
if (theStream == inputStream) {
uint8_t buffer[1024];
int len;
while ([inputStream hasBytesAvailable]) {
len = [inputStream read:buffer maxLength:sizeof(buffer)];
//...
}
}
break;
case NSStreamEventErrorOccurred:
NSLog(@"Can not connect to the host!");
break;
case NSStreamEventEndEncountered:
[theStream close];
[theStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[theStream release];
theStream = nil;
break;
default:
NSLog(@"Unknown event");
}
}
编辑:在此处找到解决方案 如何使用 NSOutputStream 的写入消息?