GCDAsyncUdpSocket的简单使用

说明:只是对GCDAsyncUdpSocket进行简单的使用,实现消息的收发。

1.导入

#import "GCDAsyncUdpSocket.h"

2.创建全局变量

//这个socket用来做发送使用 当然也可以接收

GCDAsyncUdpSocket *sendUdpSocket;

3.创建单例

static UDPManage *myUDPManage = nil;


+(instancetype)shareUDPManage{

    static dispatch_once_t onceToken;

    dispatch_once(&onceToken, ^{

        myUDPManage = [[UDPManage alloc]init];

        [myUDPManage createClientUdpSocket];

    });

    return myUDPManage;

}

4.创建socket

#pragma mark -- 创建socket

-(void)createClientUdpSocket{

    //1.创建一个 udp socket用来和服务器端进行通讯

    sendUdpSocket = [[GCDAsyncUdpSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)];

    //2.banding一个端口(可选),如果不绑定端口, 那么就会随机产生一个随机的电脑唯一的端口

    //端口数字范围(1024,2^16-1)

    NSError * error = nil;

    [sendUdpSocket bindToPort:8085 error:&error];

    //启用广播

    [sendUdpSocket enableBroadcast:YES error:&error];

    if (error) {//监听错误打印错误信息

        NSLog(@"error:%@",error);

    }else {//监听成功则开始接收信息

        [sendUdpSocket beginReceiving:&error];

    }


}

5.发送消息

-(void)startScan{

    

    NSString *s = @"mapleTest";

    NSData *data = [s dataUsingEncoding:NSUTF8StringEncoding];

    NSString *host = @"255.255.255.255";//此处如果写成固定的IP就是对特定的server监测;我这种写法是为了多方监测

    uint16_t port = 36877;//通过端口监测

    [sendUdpSocket sendData:data toHost:host port:port withTimeout:-1 tag:100];

}

6.相关的代理

#pragma mark -GCDAsyncUdpSocketDelegate

-(void)udpSocket:(GCDAsyncUdpSocket *)sock didSendDataWithTag:(long)tag{

    if (tag == 100) {

        //NSLog(@"表示标记为100的数据发送完成了");

    }

}


-(void)udpSocket:(GCDAsyncUdpSocket *)sock didNotSendDataWithTag:(long)tag dueToError:(NSError *)error{

    NSLog(@"标记为tag %ld的发送失败 失败原因 %@",tag, error);

}


-(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 *s = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

    // 继续来等待接收下一次消息

    NSLog(@"收到服务端的响应 [%@:%d] %@", ip, port, s);

    [sock receiveOnce:nil];

    //此处根据实际和硬件商定的需求决定是否主动回一条消息

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{

        [self sendBackToHost:ip port:port withMessage:s];

    });

}


- (void)udpSocketDidClose:(GCDAsyncUdpSocket *)sock withError:(NSError *)error

{

    NSLog(@"udpSocket关闭");

}


-(void)sendBackToHost:(NSString *)ip port:(uint16_t)port withMessage:(NSString *)s{

    NSString *msg = @"我收到了";

    NSData *data = [msg dataUsingEncoding:NSUTF8StringEncoding];

    [sendUdpSocket sendData:data toHost:ip port:port withTimeout:0.1 tag:200];

    

}


  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
使用组播(Multicast)协议可以实现将数据同时发送给多个设备,这在某些场景下非常有用。下面给出在 iOS 中使用 Objective-C 实现组播的基本步骤。 首先,创建一个 `GCDAsyncUdpSocket` 对象,该对象可以实现 UDP 协议的数据发送和接收。 ```objective-c #import "GCDAsyncUdpSocket.h" @interface ViewController ()<GCDAsyncUdpSocketDelegate> @property (nonatomic, strong) GCDAsyncUdpSocket *udpSocket; @property (nonatomic, strong) dispatch_queue_t udpQueue; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; self.udpQueue = dispatch_queue_create("udpQueue", DISPATCH_QUEUE_CONCURRENT); self.udpSocket = [[GCDAsyncUdpSocket alloc] initWithDelegate:self delegateQueue:self.udpQueue]; } ``` 接着,在需要发送数据的时候,调用 `sendData:toHost:port:withTimeout:tag:` 方法即可。其中,`toHost` 参数需要设置为组播组的 IP 地址,`port` 参数需要设置为组播组的端口号。 ```objective-c - (void)sendMulticastMessage:(NSString *)message { NSData *data = [message dataUsingEncoding:NSUTF8StringEncoding]; [self.udpSocket sendData:data toHost:@"224.0.0.1" port:12345 withTimeout:-1 tag:0]; } ``` 如果需要接收组播数据,需要先将 socket 绑定到组播组地址和端口号上,然后监听数据即可。代码如下: ```objective-c - (void)startListenMulticastMessage { NSError *error = nil; if (![self.udpSocket bindToPort:12345 error:&error]) { NSLog(@"Error binding: %@", error); return; } if (![self.udpSocket joinMulticastGroup:@"224.0.0.1" error:&error]) { NSLog(@"Error joining multicast group: %@", error); return; } if (![self.udpSocket enableBroadcast:YES error:&error]) { NSLog(@"Error enabling broadcast: %@", error); return; } if (![self.udpSocket beginReceiving:&error]) { NSLog(@"Error receiving: %@", error); return; } } #pragma mark - GCDAsyncUdpSocketDelegate - (void)udpSocket:(GCDAsyncUdpSocket *)sock didReceiveData:(NSData *)data fromAddress:(NSData *)address withFilterContext:(nullable id)filterContext { NSString *message = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; NSLog(@"Received multicast message: %@", message); } ``` 以上就是在 iOS 中使用组播协议发送和接收数据的基本步骤,希望对你有所帮助。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值