iOS- 移动端Socket UDP协议广播机制的实现
1.前言
2.UDP广播机制的实现
2.1.服务器端(iPad)的实现
2.1.1.先去github上下载 AsyncUdpSocket.h框架包
2.1.2.初始化udp
1
2
3
4 |
@interface
QCViewController (){ AsyncUdpSocket *asyncUdpSocket; } asyncUdpSocket = [[AsyncUdpSocket alloc] initWithDelegate: self ]; |
2.1.3.绑定端口
1
2
3
4
5
6
7
8 |
NSError
*err = nil ; [asyncUdpSocket enableBroadcast: YES
error:&err]; [asyncUdpSocket bindToPort:9527 error:&err]; //启动接收线程 [asyncUdpSocket receiveWithTimeout:-1 tag:0]; |
2.1.4.实现代理方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 |
//已接收到消息 - ( BOOL )onUdpSocket:(AsyncUdpSocket *)sock didReceiveData:( NSData
*)data withTag:( long )tag fromHost:( NSString
*)host port:(UInt16)port{ if (data是找服务器的){ //根据客户端给的IP,利用TCP或UDP 相互连接上就可以开始通讯了 } return
YES ; } //没有接受到消息 -( void )onUdpSocket:(AsyncUdpSocket *)sock didNotReceiveDataWithTag:( long )tag dueToError:( NSError
*)error{ } //没有发送出消息 -( void )onUdpSocket:(AsyncUdpSocket *)sock didNotSendDataWithTag:( long )tag dueToError:( NSError
*)error{ } //已发送出消息 -( void )onUdpSocket:(AsyncUdpSocket *)sock didSendDataWithTag:( long )tag{ } //断开连接 -( void )onUdpSocketDidClose:(AsyncUdpSocket *)sock{ } |
2.2.客户端(iPhone)的实现
注:实现步骤与服务器端相似
2.2.1.初始化udp
1
2
3
4 |
@interface
QCViewController (){ AsyncUdpSocket *asyncUdpSocket; } asyncUdpSocket = [[AsyncUdpSocket alloc] initWithDelegate: self ]; |
2.2.2.绑定端口
1
2
3
4 |
NSError
*err = nil ; [asyncUdpSocket enableBroadcast: YES
error:&err]; [asyncUdpSocket bindToPort:9527 error:&err]; |
2.2.3.实现代理方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 |
//已接收到消息 - ( BOOL )onUdpSocket:(AsyncUdpSocket *)sock didReceiveData:( NSData
*)data withTag:( long )tag fromHost:( NSString
*)host port:(UInt16)port{ return
YES ;} //没有接受到消息 -( void )onUdpSocket:(AsyncUdpSocket *)sock didNotReceiveDataWithTag:( long )tag dueToError:( NSError
*)error{ } //没有发送出消息 -( void )onUdpSocket:(AsyncUdpSocket *)sock didNotSendDataWithTag:( long )tag dueToError:( NSError
*)error{ } //已发送出消息 -( void )onUdpSocket:(AsyncUdpSocket *)sock didSendDataWithTag:( long )tag{ } //断开连接 -( void )onUdpSocketDidClose:(AsyncUdpSocket *)sock{ } |
2.2.4.广播寻找
注:广播iP地址为 255.255.255.255
1
2
3
4
5
6
7
8
9 |
NSString
*str = @ "谁是服务器?我的IP是:192.168.80.103" ; NSData *data=[str dataUsingEncoding: NSUTF8StringEncoding ]; [asyncUdpSocket sendData:data toHost:@"255.255.255.255 port:9527 withTimeout:-1 tag:0]; |
作者: 清澈Saup
出处: http://www.cnblogs.com/qingche/
本文版权归作者和博客园共有,欢迎转载,但必须保留此段声明,且在文章页面明显位置给出原文连接。
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。