objective-c下,cocatouch架構把原生的socket做了進一步的封裝,也就是stream.
添加CFNetwork架構
初始化通訊端
CFReadStreamRef readStream;CFWriteStreamRef writeStream;CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)@"127.0.0.1", 7777, &readStream, &writeStream);inputStream = ( NSInputStream *)readStream;outputStream = ( NSOutputStream *)writeStream;[inputStream setDelegate:self];[outputStream setDelegate:self];[inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];[outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];[inputStream open];[outputStream open];
訊息處理
- (void)stream:(NSStream *)theStream handleEvent:(NSStreamEvent)streamEvent {NSLog(@"stream event %i", streamEvent); NSLog(@"%@",theStream);switch (streamEvent) {case NSStreamEventOpenCompleted:NSLog(@"Stream opened");break;case NSStreamEventHasBytesAvailable: if (theStream == inputStream) {uint8_t buffer[1024]; int len;while ([inputStream hasBytesAvailable]) {len = [inputStream read:buffer maxLength:sizeof(buffer)];if (len > 0) { NSString *output = [[NSString alloc] initWithBytes:buffer length:len encoding:NSASCIIStringEncoding]; if (nil != output) { NSLog(@"server said: %@", output);[self messageReceived:output];}}}}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");} }