发送UDP广播并接收数据

本文介绍如何使用AsyncUdpSocket实现UDP广播与接收响应的过程。通过设置本地端口、发送广播请求并监听回应来建立通讯连接。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值