iOS Socket 编程
随着互联网的迅速发展,现在大部分APP都是需要网路链接,进行实时交互。如果你的APP还是本地数据,那用户体验肯定很low。今天就来研究研究网络编程之Socket。
Demo地址 TP,欢迎加qq群:489327143
首先还是先介绍一下理论知识。
网络七层由下到上分别为物理层,数据链路层,网络层,传输层,会话层,表示层和应用层。各层作用如下图
http协议,对应于应用层; tcp协议,对应于传输层;ip协议 , 对应于网络层 。
Socket的工作流程
基于TCP的socket 连接的过程
理论搞了一堆,对于一个开发来说代码才是硬货,下面来看代码。
- (IBAction)btnConnect:(UIButton *)sender { //服务端的ip地址 NSString *host = @"192.168.1.74"; int port = 8888; CFReadStreamRef readStream; CFWriteStreamRef writeStream; //连接 CFStreamCreatePairWithSocketToHost(NULL, (__bridge CFStringRef)(host), port, &readStream, &writeStream); _inputStream = (__bridge NSInputStream*)(readStream); _outputStream = (__bridge NSOutputStream*)(writeStream); _inputStream.delegate = self; _outputStream.delegate = self; [_inputStream scheduleInRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode ]; [_outputStream scheduleInRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode]; [_inputStream open]; [_outputStream open]; }
实现输入输出流的代理方法,当接受和发送时会调用下面代理
- (void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode { NSLog(@"%@",[NSThread currentThread]); switch (eventCode) { case NSStreamEventOpenCompleted: NSLog(@"输入输出流打开完成"); break; case NSStreamEventHasBytesAvailable: NSLog(@"有字节可读"); [self readData]; break; case NSStreamEventHasSpaceAvailable: NSLog(@"可以发送字节"); break; case NSStreamEventErrorOccurred: NSLog(@"连接出错"); [_inputStream close]; [_outputStream close]; [_inputStream removeFromRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode]; [_outputStream removeFromRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode]; break; default: break; } }
收到数据后会调用下面方法
- (void)readData { //本地缓存 uint8_t buf[1024]; NSInteger len =[_inputStream read:buf maxLength:sizeof(buf)]; NSData *data = [NSData dataWithBytes:buf length:len]; NSString *recStr = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]; NSLog(@"receive data :%@",recStr); }
发送方法
- (IBAction)btnSend:(UIButton *)sender { NSString *message = @"hello world"; NSData *data = [message dataUsingEncoding:NSUTF8StringEncoding]; [_outputStream write:data.bytes maxLength:data.length]; }
布局和代码都很简单,希望能达到抛砖引玉的效果。
如果你感觉上面实现比较复杂,可以使用第三方封装的库AsyncSocket,上面测试服务端就是用AsyncSocket实现的。
博客推荐