您的位置:首页 > 移动开发 > IOS开发

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

2013-02-20 20:24 465 查看
转自:http://blog.csdn.net/wudidalishi/article/details/8028301

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

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: