直接上代码 有什么问题 我随时回答
新建文件继承NSObject 我命名NetWorks
NetWorks.h文件
@property (nonatomic ) rerurnBlock returnBlock;
@property (nonatomic ) errorBlock errorBlock;
@property (nonatomic ) NSString *ipStr;
@property (nonatomic ) GCDAsyncSocket *socket;
//单例
+ (NetWorks *)sharedInstance;
//发送数据 block 使用此方法 tag 根据需求设置
- (void)sendMessage:(NSDictionary *)dic orString:(NSString *)string andTag:(long)sendTag andReturnBlock:(__autoreleasing rerurnBlock )returnBlock andError:(__autoreleasing errorBlock )errorBlock;
NetWorks.m 文件
#pragma mark 建立连接
-(void)socketConnectHost{
self.socket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
self.ipStr = [self getProperIPWithAddress:IP_ADRESS port:DKNUM];
self.socket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
[self.socket connectToHost:_ipStr onPort:DKNUM error:nil];
}
#pragma mark 创建单例
+(NetWorks *) sharedInstance
{
static NetWorks *sharedInstace = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedInstace = [[self alloc] init];
});
return sharedInstace;
}
#pragma mark 针对ipv6网络环境下适配,ipv4环境直接使用原来的地址
- (NSString*)getProperIPWithAddress:(NSString*)ipAddr port:(UInt32)port
{
NSError *addresseError = nil;
NSArray *addresseArray = [GCDAsyncSocket lookupHost:ipAddr
port:port
error:&addresseError];
if (addresseError) {
NSLog(@"错误");
}
NSString *ipv6Addr = @"";
for (NSData *addrData in addresseArray) {
if ([GCDAsyncSocket isIPv6Address:addrData]) {
ipv6Addr = [GCDAsyncSocket hostFromAddress:addrData];
}
}
if (ipv6Addr.length == 0) {
ipv6Addr = ipAddr;
}
return ipv6Addr;
}
#pragma mark 发送的数据
- (void)socket:(GCDAsyncSocket*)sock didWriteDataWithTag:(long)tag {
// NSLog(@"---发送数据的 tag---%ld---%@",tag,sock);
}
#pragma mark 连接成功
- (void)socket:(GCDAsyncSocket*)sock didConnectToHost:(NSString*)host port:(uint16_t)port {
// NSLog(@"连接成功---%@----%d",host,port);
[self.socket readDataWithTimeout:-1 tag:333];
}
#pragma mark 断开连接时候返回提示
- (void)socketDidDisconnect:(GCDAsyncSocket*)sock withError:(NSError*)err {
// 断线重连
// [self.socket connectToHost:_ipStr onPort:DKNUM error:nil];
}
#pragma mark 接受数据
- (void)socket:(GCDAsyncSocket*)sock didReadData:(NSData*)data withTag:(long)tag {
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
//block 方式
if (_returnBlock) {
_returnBlock(dic);
}
//给一个error返回
NSError *err;
if (_errorBlock) {
_errorBlock(err);
}
[self.socket disconnect];//断开连接实现一次请求
self.socket.delegate = nil;
//不用长连接所有下面方法不调用
// [self.socket readDataWithTimeout:-1 tag:tag];//持续接收服务端放回的数据
}
#pragma mark 字典转json
- (NSString*)dictionaryToJson:(NSDictionary *)dic{
NSError *parseError = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
//block 方法
- (void)sendMessage:(NSDictionary *)dic orString:(NSString *)string andTag:(long)sendTag andReturnBlock:(__autoreleasing rerurnBlock )returnBlock andError:(__autoreleasing errorBlock )errorBlock{
//每次发送数据建立连接
[self socketConnectHost];
if (dic) {
NSString *json = [self dictionaryToJson:dic];
NSData *data = [json dataUsingEncoding:NSUTF8StringEncoding];
[self.socket writeData:data withTimeout:-1 tag:sendTag];
}else{
NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
[self.socket writeData:data withTimeout:-1 tag:sendTag];
}
_returnBlock = returnBlock;
_errorBlock = errorBlock;
}
到这里 就可在使用的地方直接调用即可 使用方法如下:
//初始化连接网络请求
netWork = [NetWorks sharedInstance];
需要请求的地方
NSDictionary *dic = @{@"cmd":@"123"};
//tag 根据需求设置
[netWork sendMessage:dic orString:nil andTag:nil andReturnBlock:^(NSDictionary *dict) {
NSLog(@"register-- %@",dict);
} andError:^(NSError *error) {
//直接断开连接 错误根据后台返回数据给指点block
NSLog(@"error-- %@",error);
}];
链接: https://pan.baidu.com/s/1slWAzNJ 密码: g3p2
有问题 随时回答 QQ :527584070