标签:
先导入:AsyncUdpSocket.h、AsyncUdpSocket.m
添加<AsyncUdpSocketDelegate>协议
创建:@property (nonatomic, strong)AsyncUdpSocket *myUDPSocket;
- (void)viewDidLoad {
[super viewDidLoad];
self.myUDPSocket = [[AsyncUdpSocket alloc]initWithDelegate:self];
//绑定端口
[self.myUDPSocket bindToPort:9000 error:nil];
//开启广播
[self.myUDPSocket enableBroadcast:YES error:nil];
// 开始接收数据
[self.myUDPSocket receiveWithTimeout:-1 tag:0];
}
-(BOOL)onUdpSocket:(AsyncUdpSocket *)sock didReceiveData:(NSData *)data withTag:(long)tag fromHost:(NSString *)host port:(UInt16)port{
if (![host hasPrefix:@":"]) {
NSString *string = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"%@:%@",host,string);
}
[self.myUDPSocket receiveWithTimeout:-1 tag:0];
return YES;
}
- (IBAction)clicked:(id)sender {
[self.myUDPSocket sendData:[@"哈哈哈" dataUsingEncoding:NSUTF8StringEncoding] toHost:@"255.255.255.255" port:9000 withTimeout:-1 tag:0];
}
标签:
原文地址:http://www.cnblogs.com/stuyingiOS/p/4898884.html