iOS-----簡易地CocoaAsyncSocket使用

CocoaAsyncSocket使用

代理的.h文件

複製代碼
//GCDAsyncSocketDelegate執行代理對象

#import <Foundation/Foundation.h>
#import "CocoaAsyncSocket.h"

typedef void(^DidReadData)(NSDictionary* didReadData);
/**
 *  GCDAsyncSocketDelegate執行代理對象
 */
@interface NSObjectGCDAsyncSocket : NSObject<GCDAsyncSocketDelegate>
/**
 *  接收到數據的處理
 */
@property(nonatomic,copy)DidReadData didReadData;
/**
 *  發送的數據  若是添加新鍵值則須要先開闢內存
 */
@property(nonatomic,retain)NSMutableDictionary* writeData;
/**
 *  發送連接請求
 */
-(BOOL)startConnect;
/**
 *  單例
 */
+(NSObjectGCDAsyncSocket*)defaultSocket;

@end
複製代碼

.m文件

複製代碼
//
//  NSObjectGCDAsyncSocket.m
//  attendance


#import "NSObjectGCDAsyncSocket.h"

@implementation NSObjectGCDAsyncSocket
{
    GCDAsyncSocket* socket;
}
/**
 *  單例
 *
 *  @return
 */
+(NSObjectGCDAsyncSocket *)defaultSocket
{
    // socket只會實例化一次
    static NSObjectGCDAsyncSocket* socket=nil;
    // 保證線程安全,defaultSocket只執行一次
    static dispatch_once_t once;
    dispatch_once(&once, ^
    {
        socket=[[NSObjectGCDAsyncSocket alloc] init];
    });
    return socket;
}

/**
 *  初始化
 *
 *
 *  @return self
 */
-(instancetype)init
{
    self=[super init];
    if (self)
    {
        socket=[[GCDAsyncSocket alloc] initWithDelegate:self
                                          delegateQueue:dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)];
    }
    return self;
}
/**
 *  發送連接請求
 */
-(BOOL)startConnect
{
    // 先肯定斷開鏈接再開始連接
    if (socket.isConnected)
    {
        NSLog(@"主動斷開");
        [socket disconnect];
        
    }
    NSError* error;
    BOOL  isSuccess= [socket connectToHost:SocketHost
                                    onPort:SocketPort
                                     error:&error];
    if (error)
    {
        NSLog(@"error.localizedDescription:%@",error.localizedDescription);
    }

    return isSuccess;
    
}
#pragma mark - GCDAsyncSocketDelegate
/**
 *  連接成功
 *
 *  @param sock sock實例
 *  @param host IP
 *  @param port 端口
 */
-(void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host
         port:(uint16_t)port
{
    
//    NSLog(@"%s",__FUNCTION__);
//    NSLog(sock.isConnected?@"YES":@"NO");
//    if (sock.isConnected)
//    {

 // NSString上傳須要加"\n"分隔符方可上傳成功
/*
 [sock writeData:[@"ABCABCABCABCABCABC\n" dataUsingEncoding:NSUTF8StringEncoding]
 withTimeout:-1
 tag:0];
 */

/*
 NSDictionary* nsDictionaryUser=@{@"gpsinfo":@"Gpsinfo",
 @"pswd":self.passWord,
 @"gpstype":@(2015),
 @"name":self.name,
 };

        NSDictionary* agrement=@{@"vertion":@(1),
                                 @"type1":@(2),
                                 @"type2":@(0),
                                 @"type3":@(0)};
*/
        if ([NSJSONSerialization isValidJSONObject:self.writeData])
        {
//            NSLog(@"isValidJSONObject");
            NSError* error;
            // 先轉NSData再轉NSString是爲了保證NSDictionary格式不變
            NSData *nsDataUser= [NSJSONSerialization dataWithJSONObject:self.writeData
                                                                options:NSJSONWritingPrettyPrinted
                                                                  error:&error];
            NSString* json=[[NSString alloc] initWithData:nsDataUser
                                                 encoding:NSUTF8StringEncoding];
//            NSLog(@"nsDictionaryUser:%@",json);

            
            json=[json stringByReplacingOccurrencesOfString:@"\n"
                                                 withString:@""];
            json=[json stringByReplacingOccurrencesOfString:@" "
                                                 withString:@""];
            json=[json stringByAppendingString:@"\n"];
//            NSLog(@"json:%@",json);
            
            [sock writeData:[json dataUsingEncoding:NSUTF8StringEncoding]
                withTimeout:-1
                        tag:0];
            
            // 保持讀取的長鏈接
            [sock readDataWithTimeout:-1
                                  tag:0];

            
            if (error)
            {
                NSLog(@"localizedDescription:%@",[error localizedDescription]);
                NSLog(@"localizedFailureReason:%@",[error localizedFailureReason]);
            }
            
        }


//    }
 
}
/**
 *  發送數據成功
 *
 *  @param sock  sock實例
 *  @param tag  標記sock
 */
-(void)socket:(GCDAsyncSocket *)sock didWriteDataWithTag:(long)tag
{
//    NSLog(@"didWriteDataWithTag");
}
/**
 *  已經獲取到數據
 *
 *  @param sock sock實例
 *  @param data 獲取到的數據
 *  @param tag  標記sock
 */
-(void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data
      withTag:(long)tag
{
    
//    NSLog(@"%s",__FUNCTION__);
    NSError* error=nil;
    NSDictionary* json=(NSDictionary*)[NSJSONSerialization JSONObjectWithData:data
                                                       options:NSJSONReadingAllowFragments
                                                         error:&error];
    
    NSLog([NSJSONSerialization isValidJSONObject:json]?@"is ValidJSONObject":@"is't ValidJSONObject");
    if (error)
    {
        NSLog(@"socketError1:%@",[error localizedDescription]);
         NSLog(@"socketError2:%@",[error localizedFailureReason]);
    }
    self.didReadData(json);
    [sock disconnect];
    
}

/**
 *  連接出錯
 *
 *  @param sock sock實例
 *  @param err  錯誤參數
 */
-(void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError *)err
{
//    NSLog(@"%s",__FUNCTION__);
    
    if (err)
    {
        NSLog(@"socketDidDisconnect:%@",[err localizedDescription]);
        NSLog(@"socketDidDisconnect:%@",[err localizedFailureReason]);

    }
//    self.didReadData(nil);
}



@end
複製代碼

使用

建立對象
    socket=[NSObjectGCDAsyncSocket defaultSocket];
填寫發送的數據
socket.writeData=[NSMutableDictionary dictionaryWithDictionary:dictionary];
處理收到的數據
        socket.didReadData=^(NSDictionary* didReadData){.......}
開始連接
[socket startConnect];
添加CocoaAsyncSocket 第三庫 連接地址:https://github.com/robbiehanson/CocoaAsyncSocket
 
  
轉載自 螻蟻之毒
相關文章
相關標籤/搜索