代码改变世界

goim socket丢包粘包问题解决。

2016-12-14 16:44  xiangjune  阅读(1022)  评论(0编辑  收藏  举报

 

-(NSInteger)bytesToInt:(unsigned char*) data

{

    return (data[3]&255)|(data[2]&255)<<8|(data[1]&255)<<16|(data[0]&255)<<24;

}

 

-(NSInteger)parseDataLength:(NSData*)headerData

{

    unsigned char messageLength[4];

    [headerData getBytes:messageLength range:NSMakeRange(0, 4)];

    NSInteger messageDataLength = [self bytesToInt:messageLength];

    

    return messageDataLength;

}

 

//socket连接后收到数据

- (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)socketData withTag:(long)tag

{

    NSLog(@"socket连接后收到数据------------------------------------");

    

    switch (tag)

    {

        case TAG_PACKAGE_HEADER:

        {

            NSInteger messageDataLength = [self parseDataLength:socketData];

            if (messageDataLength == 0)

            {

                [_asyncSocket readDataToLength:TAG_PACKAGE_HEADER_LENGTH withTimeout:-1 tag:TAG_PACKAGE_HEADER];

            }

            else

            {

                [_asyncSocket readDataToLength:messageDataLength-4 withTimeout:-1 tag:TAG_PACKAGE_BODY];

            }

            break;

        }

        case TAG_PACKAGE_BODY:

        {

            [self parseSocketBodyData:socketData];

            

            [_asyncSocket readDataToLength:TAG_PACKAGE_HEADER_LENGTH withTimeout:-1 tag:TAG_PACKAGE_HEADER];

            

            break;

        }

        default:

//            [_asyncSocket readDataToLength:TAG_PACKAGE_HEADER_LENGTH withTimeout:-1 tag:TAG_PACKAGE_HEADER];

            break;

    }

    

    return;

    

}

 

 

-(void)parseSocketBodyData:(NSData *)socketData

{

    //从服务器发送的数据中减去前16字节的格式协议

    NSInteger dataLength = socketData.length;

    

    NSLog(@"data length = %ld", dataLength);

    

    Byte *inBuffer = malloc(MAX_BUFFER);

    inBuffer = (Byte *)[socketData bytes];

    BruteForceCoding *brute = [[BruteForceCoding alloc]init];

    Byte *resultByte = [brute tail:inBuffer anddataLengthLength:dataLength andHeaderLength:12];

    

    //解析指令,不同指令执行不同的操作

    NSInteger operation = [brute decodeIntBigEndian:inBuffer offset:4 size:4];

    

    //解析出body内容

    NSData *data = [NSData dataWithBytes:resultByte length:dataLength - 12];

    

    

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

    NSDictionary *rspDic = [self dictionaryWithJsonString:string];

    

}