码迷,mamicode.com
首页 > 其他好文 > 详细

CocoaAsyncSocket使用

时间:2015-11-16 19:10:28      阅读:207      评论:0      收藏:0      [点我收藏+]

标签:

代理的.h文件

//GCDAsyncSocketDelegate执行代理对象

#import <Foundation/Foundation.h>
#import "CocoaAsyncSocket.h"
#import "Public.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
//
//  Created by dgc on 15/7/7.
//  Copyright (c) 2015年 dgc. All rights reserved.
//

#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使用

标签:

原文地址:http://www.cnblogs.com/louyizhidu/p/4969592.html

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