您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 以 Objective-C 封裝二進位通訊協議的完整實作

編輯:iOS 開發綜合

在 SDK 與 socket 通訊的場景中,常會遇到二進位協議。C 語言用 struct 就能輕鬆對應協議佈局,但在 C 與 Objective-C 混用的專案裡反覆切換並不順手。本文示範如何純粹用 Objective-C 的物件導向方式完成同樣的事。

先理解 struct 到底在描述什麼

一個 C 的結構體其實只在描述四件事:協議值的佈局、每個欄位佔幾個 byte、整包的大小,以及對應的記憶體區塊。把這四件事一一映射到 Objective-C 的類別上,就能完成轉換。

假設協議定義如下:

struct {
    char           one;    // 字元
    unsigned short two;    // short 型別
    unsigned int   three;  // int 型別
    char          *four;   // 字串
} BinaryProtocolStruct;

標頭檔

@interface BinaryProtocolTest : NSObject

- (id)initWithOne:(int)one andTwo:(int)two andThree:(int)three andFour:(NSString *)string;
- (id)initWithData:(NSData *)data;

- (void)setOne:(int)one;
- (void)setTwo:(int)two;
- (void)setThree:(int)three;
- (void)setFour:(NSString *)four;

- (int)getOne;
- (int)getTwo;
- (int)getThree;
- (NSString *)getFour;

- (NSMutableData *)getProtocolData;
- (int)getProtocolSize;
+ (int)getProtocolSize;

@end

實作檔

// 協議的整體大小
#define ProtocolSize 39

@implementation BinaryProtocolTest
{
    NSMutableData *_protocolData;   // 協議的記憶體區塊
    int            _protocolSize;   // 區塊大小

    // 協議佈局:每個欄位的起始偏移與長度
    struct {
        unsigned short one_offset:8;
        unsigned short one_len:8;
        unsigned short two_offset:8;
        unsigned short two_len:8;
        unsigned short three_offset:8;
        unsigned short three_len:8;
        unsigned short four_offset:8;
        unsigned short four_len:8;
    } _protocolLayout;
}

- (void)initProtocolLayout
{
    _protocolLayout.one_offset   = 0;
    _protocolLayout.one_len      = 1;
    _protocolLayout.two_offset   = 1;
    _protocolLayout.two_len      = 2;
    _protocolLayout.three_offset = 3;
    _protocolLayout.three_len    = 4;
    _protocolLayout.four_offset  = 7;
    _protocolLayout.four_len     = 32;
    _protocolSize = 39;
}

// 封裝自己的資料
- (id)initWithOne:(int)one andTwo:(int)two andThree:(int)three andFour:(NSString *)four
{
    self = [super init];
    if (self)
    {
        [self initProtocolLayout];

        _protocolData = [[NSMutableData alloc] init];
        [_protocolData resetBytesInRange:NSMakeRange(0, _protocolSize)];

        // one 為 char,無需位元組序轉換,直接寫入
        unsigned char tempOne = one;
        [_protocolData replaceBytesInRange:NSMakeRange(_protocolLayout.one_offset, _protocolLayout.one_len)
                                  withBytes:&tempOne
                                     length:_protocolLayout.one_len];

        // two 為 unsigned short,需由主機序轉為網路序
        unsigned short tempTwo = two;
        tempTwo = htons(tempTwo);
        [_protocolData replaceBytesInRange:NSMakeRange(_protocolLayout.two_offset, _protocolLayout.two_len)
                                  withBytes:&tempTwo
                                     length:_protocolLayout.two_len];

        // three 為 unsigned int,同樣需轉換
        unsigned int tempThree = three;
        tempThree = htonl(tempThree);
        [_protocolData replaceBytesInRange:NSMakeRange(_protocolLayout.three_offset, _protocolLayout.three_len)
                                  withBytes:&tempThree
                                     length:_protocolLayout.three_len];

        // four 為字串,無需轉換
        NSData *tempFour = [four dataUsingEncoding:NSUTF8StringEncoding];
        [_protocolData replaceBytesInRange:NSMakeRange(_protocolLayout.four_offset, _protocolLayout.four_len)
                                  withBytes:tempFour.bytes
                                     length:_protocolLayout.four_len];
    }
    return self;
}

- (id)init
{
    self = [super init];
    if (self)
    {
        [self initProtocolLayout];
        _protocolData = [[NSMutableData alloc] init];
        [_protocolData resetBytesInRange:NSMakeRange(0, _protocolSize)];
    }
    return self;
}

// 從收到的封包還原物件
- (id)initWithData:(NSData *)data
{
    self = [super init];
    if (self)
    {
        [self initProtocolLayout];

        // 參數過濾:封包大小不符直接拒絕
        if (data.length != _protocolSize)
        {
            return nil;
        }

        _protocolData = [[NSMutableData alloc] init];
        [_protocolData resetBytesInRange:NSMakeRange(0, _protocolSize)];
        [_protocolData replaceBytesInRange:NSMakeRange(0, _protocolSize)
                                  withBytes:data.bytes
                                     length:_protocolSize];
    }
    return self;
}

// ---- setter ----

- (void)setOne:(int)one
{
    unsigned char tempOne = one;
    [_protocolData replaceBytesInRange:NSMakeRange(_protocolLayout.one_offset, _protocolLayout.one_len)
                              withBytes:&tempOne
                                 length:_protocolLayout.one_len];
}

- (void)setTwo:(int)two
{
    unsigned short tempTwo = htons((unsigned short)two);
    [_protocolData replaceBytesInRange:NSMakeRange(_protocolLayout.two_offset, _protocolLayout.two_len)
                              withBytes:&tempTwo
                                 length:_protocolLayout.two_len];
}

- (void)setThree:(int)three
{
    unsigned int tempThree = htonl((unsigned int)three);
    [_protocolData replaceBytesInRange:NSMakeRange(_protocolLayout.three_offset, _protocolLayout.three_len)
                              withBytes:&tempThree
                                 length:_protocolLayout.three_len];
}

- (void)setFour:(NSString *)four
{
    NSData *tempFour = [four dataUsingEncoding:NSUTF8StringEncoding];
    [_protocolData replaceBytesInRange:NSMakeRange(_protocolLayout.four_offset, _protocolLayout.four_len)
                              withBytes:tempFour.bytes
                                 length:_protocolLayout.four_len];
}

// ---- getter ----

- (int)getOne
{
    unsigned char temp;
    [_protocolData getBytes:&temp range:NSMakeRange(_protocolLayout.one_offset, _protocolLayout.one_len)];
    return temp;
}

- (int)getTwo
{
    unsigned short temp;
    [_protocolData getBytes:&temp range:NSMakeRange(_protocolLayout.two_offset, _protocolLayout.two_len)];
    return ntohs(temp);   // 網路序轉回主機序
}

- (int)getThree
{
    unsigned int temp;
    [_protocolData getBytes:&temp range:NSMakeRange(_protocolLayout.three_offset, _protocolLayout.three_len)];
    return (int)ntohl(temp);
}

- (NSString *)getFour
{
    NSData *temp = [_protocolData subdataWithRange:NSMakeRange(_protocolLayout.four_offset, _protocolLayout.four_len)];
    return [[NSString alloc] initWithUTF8String:temp.bytes];
}

- (NSMutableData *)getProtocolData
{
    return _protocolData;
}

- (int)getProtocolSize
{
    return _protocolSize;
}

+ (int)getProtocolSize
{
    return ProtocolSize;
}

@end

幾個實作上的重點與風險

位元組序轉換是關鍵。short 用 htons/ntohs,int 用 htonl/ntohl,char 與字串則不需要。寫入時轉成網路序、讀出時轉回主機序,兩端才會對得上。

原範例有兩處邏輯錯誤,這裡已修正:setter 中的條件原本寫成 if (_protocolData.length != _protocolSize),但這個判斷成立的情況是「資料尚未就緒」,反而應該在資料就緒時才寫入;getOne/getTwo/getThree 也有同樣問題。此外 getThree 原本用 unsigned char 接收 4 個 byte,會截斷資料,已改為 unsigned int。

字串欄位要注意長度。範例中 four 固定佔 32 bytes,若傳入的字串編碼後超過 32 bytes,replaceBytesInRange:withBytes:length: 的 length 參數與實際資料長度不符,會造成記憶體讀取異常。實務上應先檢查 tempFour.length <= _protocolLayout.four_len,並決定多餘空間是補 null 還是留白。

整體來說,物件導向封裝的價值在於把「資料實體」與「對資料的操作」綁在一起:位元組序轉換、長度檢查這些細節被收進類別內部,呼叫端只需要面對 get/set,不必再直接操作 raw bytes。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved