宽窄优行-由【嘉易行】项目成品而来
younger_times
2023-04-06 a1ae6802080a22e6e6ce6d0935e95facb1daca5c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
//
//  RHSocketVariableLengthEncoder.m
//  RHSocketKitDemo
//
//  Created by zhuruhong on 16/2/15.
//  Copyright © 2016年 zhuruhong. All rights reserved.
//
 
#import "RHSocketVariableLengthEncoder.h"
#import "RHSocketException.h"
#import "RHSocketUtils.h"
 
@implementation RHSocketVariableLengthEncoder
 
- (instancetype)init
{
    if (self = [super init]) {
        _maxFrameSize = 65536;
        _countOfLengthByte = 2;
        _reverseOfLengthByte = NO;
    }
    return self;
}
 
- (void)encode:(id<RHUpstreamPacket>)upstreamPacket output:(id<RHSocketEncoderOutputProtocol>)output
{
    NSData *data = [upstreamPacket dataWithPacket];
    
    if (data.length >= _maxFrameSize - _countOfLengthByte) {
        [RHSocketException raiseWithReason:@"[Encode] Too Long Frame ..."];
        return;
    }//
    
    //可变长度编码,数据块的前两个字节为后续完整数据块的长度
    NSUInteger dataLen = data.length;
    NSMutableData *sendData = [[NSMutableData alloc] init];
    
    //将数据长度转换为长度字节,写入到数据块中。这里根据head占的字节个数转换data长度,默认为2个字节
    NSData *headData = [RHSocketUtils bytesFromValue:dataLen byteCount:_countOfLengthByte reverse:_reverseOfLengthByte];
    [sendData appendData:headData];
    if (data.length > 0) {
        [sendData appendData:data];
    }
    NSTimeInterval timeout = [upstreamPacket timeout];
    
    RHSocketLog(@"[Log]: timeout: %f, sendData: %@", timeout, sendData);
    [output didEncode:sendData timeout:timeout];
}
 
@end