GCDAsyncSocket+SocketHandler.m 3.68 KB
//
//  GCDAsyncSocket+SocketHandler.m
//  Yoho
//
//  Created by Arthur on 16/6/14.
//  Copyright © 2016年 YOHO. All rights reserved.
//
#define kIphonePrivate          @"a85bb0674e08986c6b115d5e3a4884fa"
#define SOCKET_LIVE_TIMEOUT     10

#import "GCDAsyncSocket+SocketHandler.h"

@implementation GCDAsyncSocket (SocketHandler)

- (BOOL)writeDataWithParams:(NSDictionary *)params tag:(long)tag
{
    NSError *error;
    NSMutableDictionary *dic = [self encodeParams:params];//md5加密
    NSData *data = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&error];
    NSMutableData *mutaData = [NSMutableData dataWithData:data];
    [mutaData appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
//    DLog(@"发送:%@",[[NSString alloc] initWithData:mutaData encoding:NSUTF8StringEncoding]);
    if (mutaData) {
        [self writeData:mutaData withTimeout:SOCKET_LIVE_TIMEOUT tag:tag];
        [self readDataWithTimeout:-1 tag:tag];
        return YES;
    } else {
        DLog(@"请求序列化错误:%@", error);
        return NO;
    }
}

- (void)didWriteDataWithParams:(NSData *)response tag:(long)tag dataProcessingHandler:(SocketDataProcessing)handler
{
    if (response.length < 4) {
        return;
    }
    
    NSError *error;
    NSDictionary *resDic = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableContainers error:&error];
//    DLog(@"收到:%@",[[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding]);
    if (resDic) {
        if (handler) {
            handler(resDic);
        }
    } else {
        //如果解析不了  尝试拆分一下再解析
        NSString *stringRes = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
        NSArray *arr = [stringRes componentsSeparatedByString:@"}\r\n"];
        
        for (NSString *str in arr) {
            NSString *resStr = [NSString stringWithFormat:@"%@}",str];
            NSData *data = [resStr dataUsingEncoding:NSUTF8StringEncoding];
            NSError *doMoreError;
            NSDictionary *doMoreResDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&doMoreError];
            if (doMoreResDic) {
                if (handler) {
                    handler(doMoreResDic);
                }
            }
        }
        DLog(@"服务器返回数据序列化错误:%@", error);
    }
}
// md5加密
- (NSMutableDictionary *)encodeParams:(NSDictionary *)parameters
{
    NSMutableDictionary *params = [[NSMutableDictionary alloc] initWithDictionary:parameters];
    [params setObject:kIphonePrivate forKey:@"private_key"];
    NSArray *allKeys = [params allKeys];
    NSArray *sortedArray = [allKeys sortedArrayUsingSelector:@selector(compare:)];
    
    NSMutableArray *strings = [NSMutableArray array];
    for (NSString *key in sortedArray) {
        id value = [params objectForKey:key];
        if ([value isKindOfClass:[NSString class]]) {
            value = [value stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
            value = [value stringByReplacingOccurrencesOfString:@"\n" withString:@""];
            value = [value stringByReplacingOccurrencesOfString:@"\t" withString:@""];
            value = [value stringByReplacingOccurrencesOfString:@"\r" withString:@""];
        }
        [params setObject:value forKey:key];
        [strings addObject:[NSString stringWithFormat:@"%@=%@", key, value]];
    }
    NSString *source = [strings componentsJoinedByString:@"&"];
    NSString *secret = [[source md5String] lowercaseString];
    [params removeObjectForKey:@"private_key"];
    
    [params setObject:secret forKey:@"secret"];
    return params;
}

@end