iOS-----簡易地CocoaAsyncSocket使用,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上傳需要加"\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
轉載自螻蟻之毒