//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.localizedDescrGCDAsyncSocketDelegate/** * 鏈接成功 * * @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
新聞熱點
疑難解答