粗糙的iOS笔记三_socket网络通讯协议

来源:互联网 发布:算法研发工程师路线 编辑:程序博客网 时间:2024/04/30 04:07

</pre>socket   通讯协议<p></p><p>优点:安全   需三次握手</p><p>缺点:复杂<span style="white-space:pre"> </span>速度慢</p><p>需要指定IP地址 ,一个作为服务器  另一个作为客户端 ;不过都可以实现“接发”消息和文件的功能</p><p>udp<span style="white-space:pre"> </span></p><p>优点:传输速度快  简单</p><p>缺点:不安全</p><p>可以通过广播进行接发消息   适合用于群聊</p><p>演示一个简单的Demo</p><p>客户端</p><p></p><pre code_snippet_id="199399" snippet_file_name="blog_20140222_1_1345863" name="code" class="objc">#import "ViewController.h"<pre code_snippet_id="199399" snippet_file_name="blog_20140222_1_1345863" name="code" class="objc">#import "AsyncSocket.h"
@interface ViewController ()<AsyncSocketDelegate>@property (nonatomic, strong) AsyncSocket * client;@end@implementation ViewController- (void)viewDidLoad{    [super viewDidLoad];// 创建socket 客户端  记着实现委托 AsyncSocketDelegate    self.client = [[AsyncSocket alloc] initWithDelegate:self];    // 连接  指定IP地址主机  端口可自定义    [self.client connectToHost:@"192.168.1.6" onPort:8000 error:nil];    }// 添加一个Button控制发送请求- (IBAction)sendRequestForSocket:(id)sender {        // 发送请求 字符串是自定义通讯协议 此处file表示请求文件相关信息,&&符之间可继续添加相关文件的详细信息    NSString * request = [NSString stringWithFormat:@"file&& &&"];    // 初始化给定一个长度:等于是网络请求的第一部分信息head信息,方便服务器那边分析请求信息,后面可继续追加信息    NSMutableData * fileData = [NSMutableData dataWithLength:50];    // 把请求字符串 转换为UTF8编码类型的字节信息 UTF8是 通用的编码格式    NSData * data = [request dataUsingEncoding:NSUTF8StringEncoding];    // 把 data 装入 fileData    [fileData replaceBytesInRange:NSMakeRange(0, data.length) withBytes:data.bytes];    // 写/传送请求  -1表示没有超时发送 tag 暂且不管(我也不懂)    [self.client writeData:fileData withTimeout:-1 tag:0];        // 传送完请求 就要读取服务器反馈回来的信息    [self.client readDataWithTimeout:-1 tag:0];}// AsyncSocketDelegate中的读取数据方法,此方法不会自动调用,通过readDataWithTimeout:tag:方法来调用- (void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag{    // 接收数据    NSString * info = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];    NSLog(@"%@",info);        // 接收完 继续读取 保持一直读取状态    [self.client readDataWithTimeout:-1 tag:0];}- (void)onSocket:(AsyncSocket *)sock didWriteDataWithTag:(long)tag{        // 数据写完 就会调用此方法}- (void)didReceiveMemoryWarning{    [super didReceiveMemoryWarning];    // Dispose of any resources that can be recreated.}@end


/****** Server ******/#import "ViewController.h"#import "AsyncSocket.h"@interface ViewController ()<AsyncSocketDelegate>@property (nonatomic, strong) AsyncSocket * server;@property (nonatomic, strong) AsyncSocket * mySocket;@end@implementation ViewController- (void)viewDidLoad{    [super viewDidLoad];// 1.创建 服务器    self.server = [[AsyncSocket alloc] initWithDelegate:self];    // 2.监听端口    [self.server acceptOnPort:8000 error:nil];}//   3. 接收到新端口 并保持住该端口- (void)onSocket:(AsyncSocket *)sock didAcceptNewSocket:(AsyncSocket *)newSocket{    self.mySocket = newSocket;}// 4.链接到客户端- (void)onSocket:(AsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port{    // 调用读取数据的方法  因为该方法不能自动调用    [self.mySocket readDataWithTimeout:-1 tag:0];}// 读取数据- (void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag{    // 分析头部信息 前50个字节是请求的相关信息    NSData * headData = [data subdataWithRange:NSMakeRange(0, 50)];    NSString * headString = [[NSString alloc] initWithData:headData encoding:NSUTF8StringEncoding];    NSArray * headInfoes = [headString componentsSeparatedByString:@"&&"];    // 头部信息此处定义三处 用&&符分割  判断接收数据是否完整    if (headString && headInfoes.count == 3) {        NSString * type = headInfoes[0];        if ([type isEqualToString:@"file"]) {            // 写回文件信息  此处略写            NSString * fileInfo = @"文件信息已返回";            NSData * data = [fileInfo dataUsingEncoding:NSUTF8StringEncoding];            [self.mySocket writeData:data withTimeout:-1 tag:0];        }    }    // 保持一直读取    [self.mySocket readDataWithTimeout:-1 tag:0];}- (void)onSocket:(AsyncSocket *)sock didWriteDataWithTag:(long)tag{    // 写回信息后调用此方法    NSLog(@"文件已写完");}- (void)didReceiveMemoryWarning{    [super didReceiveMemoryWarning];    // Dispose of any resources that can be recreated.}@end
<span style="font-size:18px;">sock通信Demo下载:</span><a target=_blank href="http://www.400gb.com/file/68586355" target="_blank">Sockt_UDP</a>



给大家推荐一个swift视频教程,后续会不断更新,下载文件需要验证多次,有点耐心哦!

从OC转移到swift:环境与变量

swift进阶可能值

swift枚举扩展泛型

类初始化属性方法

元组闭包

变量字符串集合循环

<p></p><pre>
                                             
0 0
原创粉丝点击