ios 端UDP使用实例

GCDAsyncUdpSocket开源类库是以苹果的GCD多任务处理机制完成的一个异步交互套接字通讯。如果需要使用同步的,则去寻找AsyncUdpSocket就可以了。

github的地址:https://github.com/robbiehanson/CocoaAsyncSocket

1:  #import "GCDAsyncUdpSocket.h"和遵守协议<GCDAsyncUdpSocketDelegate>

2: 定义一个对象 @property (nonatomic, strong)GCDAsyncUdpSocket * udpSocket;

3:启动UDP:

- (void)startUDP{
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    self.udpSocket = [[GCDAsyncUdpSocket alloc]initWithDelegate:self delegateQueue:queue];
    [self.udpSocket enableBroadcast:YES error:nil];
    NSError *error = nil;
    //uint16_t port = 端口号;
    //  这个方法能接受所有此端口号发送和接受信息
//    [self.udpSocket bindToPort:port error:&error];
    [self.udpSocket enableBroadcast:YES error:&error];
    [self.udpSocket beginReceiving:nil];

}

4:心跳:

-(void)timeGet
{
    timer2 = [NSTimer scheduledTimerWithTimeInterval:10 target:self selector:@selector(heartBeat) userInfo:nil repeats:YES];
        [timer2 fire];
}
-(void)heartBeat
{
    //心跳 保持连接
    NSMutableData *writer=[[NSMutableData alloc]init];
    uint8_t *packet = malloc(3);
    memset(packet, 0, 3);
    packet[0] = 0xcf;
    packet[1] = zdID;
    packet[2] = xorSum(packet, 2, 0);
    [writer appendBytes:packet length:3];
    [self.udpSocket sendData:writer toHost:@"host" port:端口号 withTimeout:-1 tag:0];
    
}

//校验算法(c代码):
uint8_t xorSum(const uint8_t *data, uint16_t size, int index){
    if (data == 0 || size == 0) return 0;
    uint8_t sum = data[0];
    uint16_t i = 1 + index;
    for (; i < size; ++i) sum ^= data[i];
    
    return sum;

}

5:接受信息

- (void)udpSocket:(GCDAsyncUdpSocket *)sock didReceiveData:(NSData *)data fromAddress:(NSData *)address withFilterContext:(id)filterContext{
    NSString * ip = [GCDAsyncUdpSocket hostFromAddress:address];
    uint16_t port = [GCDAsyncUdpSocket portFromAddress:address];
    //自定义处理数据方法
    unsigned long length = data.length;
    uint8_t *packet = malloc(length + 1);
    memset(packet, 0, length + 1);
    [data getBytes:packet length:length];
    NSLog(@"接收到服务端的消息:ip:%@  port:%d  message:%@",ip,port,data);

    [self parseUdpPacket: packet length:length];
 
    // 协议  收到数据后 将收到的数据返回回去使用
//    if ([self.delegate respondsToSelector:@selector(clientSocketDidReceiveMessage:)]) {
//        [self.delegate clientSocketDidReceiveMessage:message];
//    }
    
    [self.udpSocket receiveOnce:nil];
//    [self.udpSocket beginReceiving:nil];

}

- (void)parseUdpPacket:(uint8_t *)packet length:(unsigned long)len {
    uint8_t cmd = packet[0];
    
    if (cmd == 0xcf) {
        // heartbeat 信息
        //....
    }else if (cmd == 0xef){  
    }
    
    else if (cmd == 0x0f) { // json protocol
      
    }
}

6:tips

NSData 转 uint8_t:

       NSData* data;

       unsigned long length = data.length;
       uint8_t *packet = malloc(length + 1);
       memset(packet, 0, length + 1);

        [data getBytes:packet length:length];

uint8_t 转 NSMutableData

 NSMutableData *writer=[[NSMutableData alloc]init];
    uint8_t *packet = malloc(3);
    memset(packet, 0, 3);
    packet[0] = 0xcf;
    packet[1] = (uint8_t类型);
    packet[2] = (uint8_t类型);
    [writer appendBytes:packet length:3];

    [self.udpSocket sendData:writer toHost:@"xxxx" port:xxx withTimeout:-1 tag:0];

uint8_t 转 NSData

        uint8_t *ptr = &packet[4];
        int json_len = packet[4] ;
        NSData * data = [NSData dataWithBytes:ptr length:json_len];

NSData 转 NSString

        NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

NSDictionary 转 NSData

    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:0 error:&error];


基本完成了NSDictionary、 NSString、NSData、uint8_t者互转





评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值