//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
//
// 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