2.1.1.先去github上下载 AsyncUdpSocket.h框架包
www.github.com
2.1.2.初始化udp
class="brush:objc;gutter:true;">@interface QCViewController (){ AsyncUdpSocket *asyncUdpSocket; } asyncUdpSocket = [[AsyncUdpSocket alloc] initWithDelegate:self];
2.1.3.绑定端口
NSError *err = nil; [asyncUdpSocket enableBroadcast:YES error:&err]; [asyncUdpSocket bindToPort:9527 error:&err]; //启动接收线程 [asyncUdpSocket receiveWithTimeout:-1 tag:0];
2.1.4.实现代理方法
//已接收到消息 - (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.1.初始化udp
@interface QCViewController (){ AsyncUdpSocket *asyncUdpSocket; } asyncUdpSocket = [[AsyncUdpSocket alloc] initWithDelegate:self];
2.2.2.绑定端口
NSError *err = nil; [asyncUdpSocket enableBroadcast:YES error:&err]; [asyncUdpSocket bindToPort:9527 error:&err];
2.2.3.实现代理方法
//已接收到消息 - (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
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/
本文版权归作者和博客园共有,欢迎转载,但必须保留此段声明,且在文章页面明显位置给出原文连接。