// // ViewController.m // stream_test // // Created by wup on 15/7/14. // Copyright (c) 2015年 wup. All rights reserved. // #import "ViewController.h" @interface ViewController () <NSStreamDelegate,NSCopying> { NSInputStream *_input; NSOutputStream *_output; } @end @implementation ViewController static ViewController *instance = nil; + (ViewController *)shareinstance { @synchronized(self) { if (!instance) { instance = [[self alloc] init]; return instance; } } return instance; } +(instancetype)allocWithZone:(struct _NSZone *)zone { @synchronized(self){ if (!instance) { instance = [super allocWithZone:zone]; return instance; } } return instance; } -(id)copyWithZone:(NSZone *)zone { return self; } - (void)viewDidLoad { [super viewDidLoad]; NSString *connHost = @"127.0.0.1"; CFReadStreamRef readstream; CFWriteStreamRef writestream; CFStreamCreatePairWithSocketToHost(NULL, (__bridge CFStringRef)(connHost), 50000, &readstream, &writestream); _input = (__bridge NSInputStream *)(readstream); _output = (__bridge NSOutputStream *)(writestream); _input.delegate = self; _output.delegate = self; // 添加到主运行循环 [_input scheduleInRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes]; [_output scheduleInRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes]; // 打开流传输 [_input open]; [_output open]; } -(void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode { //stream事件 // NSStreamEventNone = 0, // NSStreamEventOpenCompleted = 1UL << 0, 流打开完毕 // NSStreamEventHasBytesAvailable = 1UL << 1, 有字节读取 // NSStreamEventHasSpaceAvailable = 1UL << 2, 可以发送 // NSStreamEventErrorOccurred = 1UL << 3, 发生错误 // NSStreamEventEndEncountered = 1UL << 4 链接断开 // switch (eventCode) { case NSStreamEventOpenCompleted: NSLog(@"%@ NSStreamEventOpenCompleted",aStream); break; case NSStreamEventHasBytesAvailable: NSLog(@"%@ NSStreamEventHasBytesAvailable",aStream); [self readdata]; break; case NSStreamEventHasSpaceAvailable: NSLog(@"%@ NSStreamEventHasSpaceAvailable",aStream); break; case NSStreamEventErrorOccurred: NSLog(@"%@ NSStreamEventErrorOccurred",aStream); break; case NSStreamEventEndEncountered: NSLog(@"%@ NSStreamEventEndEncountered",aStream); [_input close]; [_output close]; break; default: break; } } -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { [self writeData]; } -(void)writeData { NSString *msgstr = @"nihao!\r\n"; NSData *msgdata = [msgstr dataUsingEncoding:NSUTF8StringEncoding]; [_output write:msgdata.bytes maxLength:msgdata.length]; } -(void)readdata { uint8_t buf[2048]; NSInteger buffint = [_input read:buf maxLength:sizeof(buf)]; NSData *msgdata = [NSData dataWithBytes:buf length:buffint]; NSString *recstr = [[NSString alloc] initWithData:msgdata encoding:NSUTF8StringEncoding]; NSLog(@"%@",recstr); } @end