码迷,mamicode.com
首页 > 移动开发 > 详细

ios开发之发送UDP广播并接收数据

时间:2015-07-31 01:21:56      阅读:137      评论:0      收藏:0      [点我收藏+]

标签:udp   通讯   xcode   ios开发   

用了asyncUdpSocket, 服务端在接收到广播后,就会做出回应,然后就可以开始通讯了。
 

- (void)init{

     AsyncUdpSocket *socket=[[AsyncUdpSocketalloc]initWithDelegate:self];

     [socketlocalPort:16747];

     NSTimeInterval timeout=5000;

     NSString *request=@"quick_stat";

     NSData *data=[NSDatadataWithData:[request dataUsingEncoding:NSASCIIStringEncoding] ];

     UInt16 port=8081;  

     NSError *error;

     [socket enableBroadcast:YESerror:&error];


     [socket sendData :data toHost:@"255.255.255.255" port:port withTimeout:timeout tag:1];

     [socket receiveWithTimeout:-1tag:0];

     NSLog(@"begin scan");

}

- (BOOL)onUdpSocket:(AsyncUdpSocket *)sock didReceiveData:(NSData *)data withTag:(long)tag fromHost:(NSString *)host port:(UInt16)port{

      NSString* result;

      result = [[NSStringalloc] initWithData:data encoding:NSASCIIStringEncoding];

      NSLog(@"%@",result);

      NSLog(@"received");

}

-(BOOL)onUdpSocket:(AsyncUdpSocket *)sock didNotReceiveDataWithTag:(long)tag dueToError:(NSError *)error{

       NSLog(@"not received");

}

-(BOOL)onUdpSocket:(AsyncUdpSocket *)sock didNotSendDataWithTag:(long)tag dueToError:(NSError *)error{

        NSLog(@"%@",error);

        NSLog(@"not send");

}

-(BOOL)onUdpSocket:(AsyncUdpSocket *)sock didSendDataWithTag:(long)tag{

        NSLog(@"send");

}

-(BOOL)onUdpSocketDidClose:(AsyncUdpSocket *)sock{

        NSLog(@"closed");

}

版权声明:本文为博主原创文章,未经博主允许不得转载。

ios开发之发送UDP广播并接收数据

标签:udp   通讯   xcode   ios开发   

原文地址:http://blog.csdn.net/yangchen9931/article/details/47160799

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!