TCP与UDP(实时通讯)

1.TCP使用

导入AsyncSocket资源文件夹,此文件是arc混编,加入库文件,如下图:

 1 #import "ViewController.h"
 2 #import "AsyncSocket.h"
 3 
 4 @interface ViewController () <AsyncSocketDelegate>{
 5     
 6     AsyncSocket *_recvSocket;  //服务端
 7     AsyncSocket *_sendSocket;  //客户端
 8     
 9     NSMutableArray *_socketArray; //数组用于记录socket
10     
11 }
12 
13 @end
14 
15 @implementation ViewController
16 
17 - (void)viewDidLoad {
18     [super viewDidLoad];
19 
20     //初始化数组
21     _socketArray = [[NSMutableArray alloc] init];
22     
23     //服务端  负责监听有没有客户端连接
24     _recvSocket = [[AsyncSocket alloc] initWithDelegate:self];
25     
26     //客户端
27     _sendSocket = [[AsyncSocket alloc] initWithDelegate:self];
28     
29     //服务端开始监听 端口5678
30     [_recvSocket acceptOnPort:5678 error:nil];
31 
32 }
33 
34 //如果监听到有人连接,那么久会调用此方法
35 - (void)onSocket:(AsyncSocket *)sock didAcceptNewSocket:(AsyncSocket *)newSocket {
36     //保存服务端的新的套接字  (谁连接就保存谁)
37     [_socketArray addObject:newSocket];
38     //等待客户端发来的新消息 ,必须写 否则没有数据过来
39     [newSocket readDataWithTimeout:-1 tag:0];
40     
41 }
42 
43 //如果监听到客户端发送来的消息,就会执行此方法
44 - (void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag {
45     
46     NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
47     
48     //拼接内容 显示
49     self.showTextView.text = [NSString stringWithFormat:@"%@%@:%@
",self.showTextView.text,sock.connectedHost,str];
50 
51     //继续监听客户端发送的消息
52     [sock readDataWithTimeout:-1 tag:0];
53 }
54 
55 //连接成功后调用此方法
56 - (void)onSocket:(AsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port {
57     NSLog(@"连接成功");
58 }
59 
60 //端口连接调用此方法
61 - (void)onSocketDidDisconnect:(AsyncSocket *)sock {
62     
63     NSLog(@"断开连接");
64 }
65 
66 //当消息发送出去后调用此方法
67 - (void)onSocket:(AsyncSocket *)sock didWriteDataWithTag:(long)tag {
68     NSLog(@"消息发送");
69 }
70 
71 
72 
73 - (void)didReceiveMemoryWarning {
74     [super didReceiveMemoryWarning];
75     // Dispose of any resources that can be recreated.
76 }
77 
78 - (IBAction)connect:(id)sender {
79     //首先判断连接状态,如果连接了 先端口连接 然后重新连接
80     if (_sendSocket.isConnected) {
81         //如果连接了 断开连接
82         [_sendSocket disconnect];
83     }
84     //客户端连接host 注意:ip和端口别写错了 否则连接不上
85     [_sendSocket connectToHost:self.ipTextField.text onPort:5678 error:nil];
86     
87 }
88 
89 - (IBAction)send:(id)sender {
90     
91     NSData *data = [self.contentTextField.text dataUsingEncoding:NSUTF8StringEncoding];
92     //客户端发送数据
93     [_sendSocket writeData:data withTimeout:30 tag:0];
94     
95     self.showTextView.text = [NSString stringWithFormat:@"%@我说:%@
",self.showTextView.text,self.contentTextField.text];
96     //清空发送输入空内容
97     self.contentTextField.text = @"";
98 }
99 @end

2.UDP使用

导入AsyncSocket资源文件夹,此文件是arc混编,加入库文件,操作如1中上图:

 1 #import "ViewController.h"
 2 #import "AsyncUdpSocket.h"
 3 
 4 @interface ViewController () <AsyncUdpSocketDelegate>{
 5     
 6     AsyncUdpSocket *_sendSocket;    //客户端  发数据
 7     AsyncUdpSocket *_recvSocket;    //服务端  接数据
 8 }
 9 @property (weak, nonatomic) IBOutlet UITextField *ipTextField;
10 @property (weak, nonatomic) IBOutlet UITextField *contentTextField;
11 @property (weak, nonatomic) IBOutlet UITextView *showTextView;
12 - (IBAction)send:(id)sender;
13 @end
14 
15 @implementation ViewController
16 
17 - (void)viewDidLoad {
18     [super viewDidLoad];
19 
20     //创建客户端 参数代理self
21     _sendSocket = [[AsyncUdpSocket alloc] initWithDelegate:self];
22     //客户端绑定一个端口
23     [_sendSocket bindToPort:5677 error:nil];
24     
25     
26     //创建服务端  参数代理self
27     _recvSocket = [[AsyncUdpSocket alloc] initWithDelegate:self];
28     //服务端绑定端口
29     [_recvSocket bindToPort:5678 error:nil];
30     
31     
32     //服务端开始等待接收数据(消息) -1代表一直等待 如果是正数 比如5 代表等待5秒  tag:标识
33     [_recvSocket receiveWithTimeout:-1 tag:0];
34     
35 }
36 
37 //服务端接收到数据会调用这个方法
38 - (BOOL)onUdpSocket:(AsyncUdpSocket *)sock didReceiveData:(NSData *)data withTag:(long)tag fromHost:(NSString *)host port:(UInt16)port {
39     /*
40      第一个参数:udpSocket
41      第二个参数:发送过来的内容  NSData类型
42      第三个参数:tag标识
43      第四个参数:host 这里是ip地址
44      第五个参数:端口号
45      */
46     
47     
48     //将NSData类型转字符串
49     NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
50     NSLog(@"str:%@",str);
51     if (str) {
52         self.showTextView.text = [NSString stringWithFormat:@"%@%@:%@
",self.showTextView.text,host,str];
53     }
54     //继续等待接收的数据,注:必须要加否则下次收到消息无法得到
55     [_recvSocket receiveWithTimeout:-1 tag:0];
56     
57     return YES;
58 }
59 
60 - (void)onUdpSocket:(AsyncUdpSocket *)sock didSendDataWithTag:(long)tag {
61     NSLog(@"UDP 发送消息");
62 }
63 
64 
65 - (void)didReceiveMemoryWarning {
66     [super didReceiveMemoryWarning];
67     // Dispose of any resources that can be recreated.
68 }
69 
70 - (IBAction)send:(id)sender {
71     
72     //取出self.contentTextField输入框的文本内容 然后转NSData类型
73     NSData *data = [self.contentTextField.text dataUsingEncoding:NSUTF8StringEncoding];
74     //客户端发送内容
75     /*
76      第一个参数:发送内容 NSData类型
77      第二个参数:ip地址  发给谁
78      第三个参数:端口号
79      第四个参数:超时时间 30秒 超过30秒后不会做任何处理
80      第五个参数:标识
81      */
82     
83     [_sendSocket sendData:data toHost:self.ipTextField.text port:5678 withTimeout:30 tag:0];
84 }
85 @end
原文地址:https://www.cnblogs.com/GJ-ios/p/5483522.html