美文网首页iOS 好东西
iOS socket 接收byte数组(NSMutableDat

iOS socket 接收byte数组(NSMutableDat

作者: 旅途开发者 | 来源:发表于2018-08-10 15:44 被阅读432次

    发送的时候,NSMutableData是将数据通过

    • -(void)appendBytes:(const void *)bytes length:(NSUInteger)length

    这个方法把数据拼接起来:详细拼接,但是拼接的时候要处理好每个数据类似的长度(64位系统下,因为苹果基本上放弃32位系统了)

    Float类型的sizeof  -----   4个字节
    CGFloat类型的sizeof  -----   8个字节
    Double类型的sizeof  -----   8个字节
    Int类型的sizeof  -----   8个字节
    int_fast8_t类型的sizeof  -----   1个字节
    int_fast16_t类型的sizeof  -----   2个字节
    int_fast32_t类型的sizeof  -----   4个字节
    int_fast64_t类型的sizeof  -----   8个字节
    intmax_t类型的sizeof  -----   8个字节
    NSInteger类型的sizeof  -----   8个字节
    NSNumber类型的sizeof  -----   8个字节
    float_t类型的sizeof  -----   4个字节
    Float32类型的sizeof  -----   4个字节
    Float64类型的sizeof  -----   8个字节
    Float80类型的sizeof  -----   16个字节
    double_t类型的sizeof  -----   8个字节
    CLong类型的sizeof  -----   8个字节
    CC_LONG类型的sizeof  -----   4个字节
    CChar16类型的sizeof  -----   2个字节
    CChar类型的sizeof  -----   1个字节
    

    当接收数据的时候,就要按照每种类型的所占字节数进行分割二进制数据,然后再转换,例如:

        NSMutableData *mutableData = [[NSMutableData alloc] init];
        
        //这里用三种数据类型写入
        NSInteger mobile = 11111;   // 8 位
        NSString * lastsend = @"测试的数据";  //  字符串要转为data才能写入
        int kind = 3212;  //  4 位
        
        //拼接到二进制文件中
        [mutableData appendBytes:&mobile length:sizeof(mobile)];
        
        //字符串类型数据要转成 NSData 才能写入
        NSData * data0 = [lastsend dataUsingEncoding:NSUTF8StringEncoding];
        [mutableData appendData:data0];
        
        [mutableData appendBytes:&kind length:sizeof(kind)];
    
        //开始读取(NSInteger 类型是8位)
        NSInteger mobileBuffer = 0;
        [mutableData getBytes:&mobileBuffer range:NSMakeRange(0, sizeof(NSInteger))];
        
        //因为不确定 NSData 类型的位数,所以这里先减去 Int 类型和 NSInteger 类型的位数,最后的就是字符串数据
        NSData * lastsendData = [mutableData subdataWithRange:NSMakeRange(8, mutableData.length - sizeof(NSInteger) - sizeof(int))];
        NSString * str = [[NSString alloc]initWithData:lastsendData encoding:NSUTF8StringEncoding];
        
        //开始读取 (Int 类型 4 位)
        int kindBuffer = 0;
        [mutableData getBytes:&kindBuffer range:NSMakeRange(mutableData.length - 4, sizeof(int))];
        
        NSLog(@"解析的数据。 %ld  %@  %d",mobileBuffer,str,kindBuffer);
    

    相关文章

      网友评论

        本文标题:iOS socket 接收byte数组(NSMutableDat

        本文链接:https://www.haomeiwen.com/subject/xlikbftx.html