因为后台数据量的增加 虽然udp不稳定但是对于大量数据的传输还是必不可少的 所以需要简单说一下最新GCDAsyncUdpSocket的用法
首先新建一个NSObject 类 在.h文件实现如下代码
#import <Foundation/Foundation.h>
#import "GCDAsyncUdpSocket.h"
//IP
#define SERVER_HOST @"192.168.0.1"
//端口
#define SERVER_PORT 10000
#define TIMEOUT -1
typedef void(^ReturnMsg)(NSDictionary *dic,NSString *msg);
typedef void(^ReturnError)(NSError *error);
@interface GCDSocketTools : NSObject <GCDAsyncUdpSocketDelegate>
@property (nonatomic )GCDAsyncUdpSocket *udpSocket;
@property (nonatomic ) ReturnMsg returnMsg;
@property (nonatomic ) ReturnError returnError;
//单例初始化
+ (instancetype)sharedInstance;
//发送消息的函数
- (void )sendDict:(NSDictionary *)dict OrString:(NSString *)string retrunMsg:(__autoreleasing ReturnMsg )returnMsg returnError:(__autoreleasing ReturnError ) returnError andTag:(long)tag;
@end
然后在.m 中实现
#import "GCDSocketTools.h"
@implementation GCDSocketTools
#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];
}
- (void )sendDict:(NSDictionary *)dict OrString:(NSString *)string retrunMsg:(__autoreleasing ReturnMsg )returnMsg returnError:(__autoreleasing ReturnError ) returnError andTag:(long)tag{
if (dict) {
NSString *json = [self dictionaryToJson:dict];
NSData *data = [json dataUsingEncoding:NSUTF8StringEncoding];
[self.udpSocket sendData:data toHost:SERVER_HOST port:SERVER_PORT withTimeout:TIMEOUT tag:tag];
}else{
NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
[self.udpSocket sendData:data toHost:SERVER_HOST port:SERVER_PORT withTimeout:TIMEOUT tag:tag];
}
self.returnMsg = returnMsg;
self.returnError = returnError;
}
#pragma mark - socket协议方法
-(void)udpSocket:(GCDAsyncUdpSocket *)sock didReceiveData:(NSData *)data fromAddress:(NSData *)address withFilterContext:(id)filterContext{
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
NSString *s = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
if (_returnMsg) {
_returnMsg(dic,s);
}
NSError *err=nil;
//接受完上边的数据 再次启动一个等待
[sock receiveOnce:&err];
// NSString *ip = [GCDAsyncUdpSocket hostFromAddress:address];
// uint16_t port = [GCDAsyncUdpSocket portFromAddress:address];
// 继续来等待接收下一次消息
// dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
// [self sendBackToHost:ip port:port withMessage:s];
// });
}
//没有接受到消息
-(void)onUdpSocket:(GCDAsyncUdpSocket *)sock didNotReceiveDataWithTag:(long)tag dueToError:(NSError *)error{
if (_returnError) {
_returnError(error);
}
}
//没有发送出消息
-(void)onUdpSocket:(GCDAsyncUdpSocket *)sock didNotSendDataWithTag:(long)tag dueToError:(NSError *)error{
if (_returnError) {
_returnError(error);
}
}
//已发送出消息
-(void)onUdpSocket:(GCDAsyncUdpSocket *)sock didSendDataWithTag:(long)tag{
NSLog(@"%ld",tag);
}
//断开连接
-(void)onUdpSocketDidClose:(GCDAsyncUdpSocket *)sock{
NSLog(@"断开连接");
}
#pragma mark - 懒加载
- (GCDAsyncUdpSocket *)udpSocket{
if (!_udpSocket) {
dispatch_queue_t dQueue = dispatch_queue_create("client udp socket", NULL);
//1.创建一个 udp socket用来和服务器端进行通讯
_udpSocket = [[GCDAsyncUdpSocket alloc] initWithDelegate:self delegateQueue:dQueue socketQueue:nil];
//2.banding一个端口(可选),如果不绑定端口, 给个空 就会随机产生一个随机的电脑唯一的端口
//端口数字范围(1024,2^16-1)
NSError *err;
[_udpSocket bindToPort:(uint16_t)nil error:&err];
//3.等待接收对方的消息
[_udpSocket receiveOnce:&err];
}
return _udpSocket;
}
#pragma mark - 初始化单例对象
+ (instancetype)sharedInstance{
static GCDSocketTools *socketConnect = nil;
static dispatch_once_t oneToken;
dispatch_once(&oneToken, ^{
socketConnect = [[GCDSocketTools alloc]init];
});
return socketConnect;
}
-(void)dealloc{
NSLog(@"%s",__func__ );
[_udpSocket close];
_udpSocket = nil;
}
@end
这样在使用的时候导入头文件 #import "GCDSocketTools.h"
[[GCDSocketTools sharedInstance] sendDict:nil OrString:@"ddd" retrunMsg:^(NSDictionary *dic, NSString *msg) {
NSLog(@"%@---%@",dic, msg);
} returnError:^(NSError *error) {
NSLog(@"---%@",error);
} andTag:10003];
网友评论