Socket简单介绍(通过NSStream)
Socket通过io传输,以二进制流的方式(数据流)对数据进行传输。数据在两端的Socket之间通过io进行传输数据。通过客户端和服务器之间传输数据。
IOS以NSStream的方式来发送数据和接受数据。通过数据流的代理对数据的变化做出响应。
建立连接的步骤:
1.设置网络连接,绑定主机和端口
2.设置输入和输出流的代理,监听数据的变化状态
3.将输入输出流添加至runloop。
4.打开输入和输出流
5.接受消息或者发送数据
6.读取输入流的数据和
7.到达数据流末尾时,关闭数据流,移除runloop
数据流的状态枚举:
/* NSStreamEventNone // 无事件 NSStreamEventOpenCompleted // 建立连接完成 NSStreamEventHasBytesAvailable // 有可读的字节,接收到了数据,可以读了 NSStreamEventHasSpaceAvailable // 可以使用输出流的空间,此时可以发送数据给服务器 NSStreamEventErrorOccurred // 发生错误 NSStreamEventEndEncountered // 流结束事件,在此事件中负责做销毁工作 */
实例:
1.添加队列
NSThread *thread = [[NSThread alloc]initWithTarget:self selector:@selector(loadDataServer:) object:url]; [thread start];//添加队列
2.设置网络连接和代理等一系列设置
-(void)loadDataServer:(NSURL *)url { CFReadStreamRef readStream; CFWriteStreamRef writeStream; CFStreamCreatePairWithSocketToHost(NULL, (__bridge CFStringRef)([url host]), [[url port] integerValue], &readStream, &writeStream);//建立连接 _input = (__bridge NSInputStream *)(readStream); _output = (__bridge NSOutputStream *)(writeStream); _input.delegate = self;//设置代理 [_input scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];//添加到runloop [_input open];//打开 _output.delegate = self; [_output scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; [_output open]; [[NSRunLoop currentRunLoop]run]; }
3.查看数据流状态
//设置对应代理 -(void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode { switch (eventCode) { case NSStreamEventNone: { //无事件; } break; case NSStreamEventOpenCompleted: { //建立连接完成 } break; //接收到数据,有可读字节 case NSStreamEventHasBytesAvailable: { if (_receivedData == nil) { _receivedData = [[NSMutableData alloc]init]; } uint8_t buffer[1024]; NSInteger numBtyes = [(NSInputStream *)aStream read:buffer maxLength:sizeof(buffer)]; if (numBtyes > 0) { NSString *str = [[NSString alloc]initWithBytes:buffer length:numBtyes encoding:NSUTF8StringEncoding]; NSLog(@"%@",str); } } break; case NSStreamEventHasSpaceAvailable: { //可以写入数据 } break; case NSStreamEventErrorOccurred: { //发生错误 } break; case NSStreamEventEndEncountered: { //流结束,此处进行销毁 [aStream close]; [aStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; } break; default: break; } }
4.发送数据
- (IBAction)click:(id)sender { NSString *mytext = @"moxue"; NSData *data = [mytext dataUsingEncoding:NSUTF8StringEncoding]; [_output write:data.bytes maxLength:data.length]; }