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

用了 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");

}

  • 0
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值