CocoaAsyncSocket使用
代理的.h文件
#import <Foundation/Foundation.h> #import "GCDAsyncSocket.h" typedef void(^SR_DidReadData)(NSDictionary* didReadData); /* */ @interface SocketRequest : NSObject<GCDAsyncSocketDelegate> @property(nonatomic,copy)SR_DidReadData sr_DidReadData; @property(nonatomic,retain)NSDictionary* sr_WriteData; /** * 单例 */ +(SocketRequest*)defaultSocket; /** * 发送链接请求 */ -(void)sr_StartConnect_WriteData:(NSDictionary*)writeData ReviceData:(SR_DidReadData)reviceData;
.m文件
#import "SocketRequest.h" #import "Public.h" NSString* BoolValue(BOOL value) { if (value) { return @"YES"; } return @"NO"; } @implementation SocketRequest { GCDAsyncSocket* socket; } /** * 单例 */ +(SocketRequest *)defaultSocket { //socket只会实例化一次 static SocketRequest* socket=nil; //保证线程安全,defaultSocket只执行一次 static dispatch_once_t once; dispatch_once(&once, ^ { socket=[[SocketRequest alloc] init]; }); return socket; } /** * 初始化 */ -(instancetype)init { self=[super init]; if (self) { socket=[[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)]; } return self; } /** * 发送链接请求 */ -(void)sr_StartConnect_WriteData:(NSDictionary*)writeData ReviceData:(SR_DidReadData)reviceData { //先确定断开连接再开始链接 FunctionLog(@"%@",BoolValue(socket.isConnected)); if (socket.isConnected) { [socket disconnect]; } self.sr_WriteData=writeData; self.sr_DidReadData = reviceData; NSError* error; /* 判断不准(目标地址未开判断为YES) */ [socket connectToHost:SocketHost onPort:SocketPort error:&error]; if (!socket.isConnected) { if (self.sr_DidReadData) { self.sr_DidReadData(nil); } } } #pragma mark - <GCDAsyncSocketDelegate> /** * 发送数据成功 */ -(void)socket:(GCDAsyncSocket *)sock didWriteDataWithTag:(long)tag { FunctionLog(@"socket_Success"); } /** * 已经获取到数据 */ -(void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag { NSError* error=nil; id json=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error]; if (error) { FunctionLog(@"%@",error.localizedDescription); } else { if ([NSJSONSerialization isValidJSONObject:json]) { FunctionLog(@"%@",json); if (self.sr_DidReadData) { self.sr_DidReadData(json); } } } [sock disconnect]; } /** * 链接出错 */ -(void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError *)err { if (err) { FunctionLog(@"%@",err.localizedDescription); if (self.sr_DidReadData) { self.sr_DidReadData(nil); } } } /** * 链接成功 */ -(void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(uint16_t)port { if ([NSJSONSerialization isValidJSONObject:self.sr_WriteData]) { NSError* error; //先转nsdata再转nsstring是为了保证nsdictionary格式不变 NSData *nsDataUser= [NSJSONSerialization dataWithJSONObject:self.sr_WriteData options:NSJSONWritingPrettyPrinted error:&error]; NSString* json=[[NSString alloc] initWithData:nsDataUser encoding:NSUTF8StringEncoding]; json=[json stringByReplacingOccurrencesOfString:@"\n" withString:@""]; json=[json stringByReplacingOccurrencesOfString:@" " withString:@""]; json=[json stringByAppendingString:@"\n"]; /* 数据发送 */ [sock writeData:[json dataUsingEncoding:NSUTF8StringEncoding] withTimeout:30 tag:0]; /* 数据读取 */ [sock readDataWithTimeout:5 tag:1]; if (error) { FunctionLog(@"%@",error.localizedDescription); } } } @end
//nsstring上传需要加"\n"分隔符方可上传成功
/* [sock writeData:[@"ABCABCABCABCABCABC\n" dataUsingEncoding:NSUTF8StringEncoding] withTimeout:-1 tag:0]; */
使用
[[SocketRequest defaultSocket] sr_StartConnect_WriteData:@{} ReviceData:^(NSDictionary *didReadData) {}];