码迷,mamicode.com
首页 > 移动开发 > 详细

iOS-----简易地CocoaAsyncSocket使用

时间:2015-11-17 12:42:54      阅读:171      评论:0      收藏:0      [点我收藏+]

标签:

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

转载自蝼蚁之毒

iOS-----简易地CocoaAsyncSocket使用

标签:

原文地址:http://www.cnblogs.com/congli0220/p/4971182.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!