zoukankan      html  css  js  c++  java
  • 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上传需要加"
    "分隔符方可上传成功
    /*
     [sock writeData:[@"ABCABCABCABCABCABC
    " 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:@"
    "
                                                     withString:@""];
                json=[json stringByReplacingOccurrencesOfString:@" "
                                                     withString:@""];
                json=[json stringByAppendingString:@"
    "];
    //            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
    
    
    转载自蝼蚁之毒
  • 相关阅读:
    短信平台README.MD
    电子保单README.MD
    数据结构和算法(二)
    学习java数据结构和算法笔记(一)
    删除SVN信息
    工作中比较经常用到的命令
    Eclipse不正常关闭后,解决闪退问题
    文字接口数据捕获tcpdump
    Swagger2和springMVC整合测试
    SpringMybatis 整合JavaWeb
  • 原文地址:https://www.cnblogs.com/congli0220/p/4971182.html
Copyright © 2011-2022 走看看