需求是iOS端发送udp消息指令,中控接收端接收做出相应变化。用的GCDAsyncUdpSocket,直接pod导入或者github下载加入项目中
这里是客户端,新建一个单例模式UDPManage类,记得导入GCDAsyncUdpSocket和遵守协议
#define udpPort 6666
@interface UDPManage()<GCDAsyncUdpSocketDelegate>
@property (nonatomic, strong)GCDAsyncUdpSocket *udpSocket;
@end
static UDPManage *myUDPManage = nil;
@implementation UDPManage
+(instancetype)shareUDPManage{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
myUDPManage = [[UDPManage alloc]init];
[myUDPManage creatClientUdpSocket];
});
return myUDPManage;
}
-(void)creatClientUdpSocket{
self.udpSocket = [[GCDAsyncUdpSocket alloc]initWithDelegate:self delegateQueue:dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)];
//绑定端口
NSError *error = nil;
[self.udpSocket bindToPort:udpPort error:&error];
//广播
[self.udpSocket enableBroadcast:YES error:&error];
if (error) {
NSLog(@"error:%@",error);
}else{
[self.udpSocket beginReceiving:&error];
}
}
-(void)broadcast{
//消息内容
NSString *str = @"这是一个测试广播";
NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
//如果向特定ip发送,这里要写明ip
NSString *host = @"255.255.255.255";
[self.udpSocket sendData:data toHost:host port:udpPort withTimeout:-1 tag:100];
}
//成功
-(void)udpSocket:(GCDAsyncUdpSocket *)sock didSendDataWithTag:(long)tag{
NSLog(@"发送成功嘞");
}
//失败
-(void)udpSocket:(GCDAsyncUdpSocket *)sock didNotSendDataWithTag:(long)tag dueToError:(NSError *)error{
NSLog(@"发送失败嘞,错误信息是:%@",error);
}
调用就直接
[[UDPManage shareUDPManage]broadcast];
服务端接收写了个简单的测试Demo
- (void)viewDidLoad {
[super viewDidLoad];
dispatch_queue_t dQueue = dispatch_queue_create("", NULL);
self.receiveSocket = [[GCDAsyncUdpSocket alloc]initWithDelegate:self delegateQueue:dQueue];
NSError *error;
//记得绑定端口,和客户端对应的
[self.receiveSocket bindToPort:severPort error:&error];
if (error) {
NSLog(@"服务器绑定失败");
}
[self.receiveSocket beginReceiving:nil];
}
//接收到消息后的协议方法
-(void)udpSocket:(GCDAsyncUdpSocket *)sock didReceiveData:(NSData *)data fromAddress:(NSData *)address withFilterContext:(id)filterContext{
NSString *ip = [GCDAsyncUdpSocket hostFromAddress:address];
uint16_t port = [GCDAsyncUdpSocket portFromAddress:address];
NSString *str = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"我收到了ip:%@,port:%hu,内容是:%@ 的消息",ip,port,str);
//写了个弹框展示收到的消息
UIAlertController* alert = [UIAlertController alertControllerWithTitle:[NSString stringWithFormat:@"ip:%@, port:%hu",ip,port]
message:[NSString stringWithFormat:@"内容是:%@",str]
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action) {
//响应事件
NSLog(@"action = %@", action);
}];
UIAlertAction* cancelAction = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action) {
//响应事件
NSLog(@"action = %@", action);
}];
[alert addAction:defaultAction];
[alert addAction:cancelAction];
[self presentViewController:alert animated:YES completion:nil];
}