建站代码网

热门标签

Socket简单介绍(通过NSStream)

     Socket通过io传输,以二进制流的方式(数据流)对数据进行传输。数据在两端的Socket之间通过io进行传输数据。通过客户端和服务器之间传输数据。

     IOS以NSStream的方式来发送数据和接受数据。通过数据流的代理对数据的变化做出响应。

     建立连接的步骤:

      1.设置网络连接,绑定主机和端口

      2.设置输入和输出流的代理,监听数据的变化状态

      3.将输入输出流添加至runloop。

      4.打开输入和输出流

      5.接受消息或者发送数据

      6.读取输入流的数据和

      7.到达数据流末尾时,关闭数据流,移除runloop

 

     数据流的状态枚举:

实例:

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;

热门信息

X