本文是基于scoket通信的tcp来进行数据的json格式传输与获取的。
首先,我们先要下载AsyncSockethttps://github.com/robbiehanson/CocoaAsyncSocket类库,将RunLoop文件夹下的AsyncSocket.h, AsyncSocket.m, AsyncUdpSocket.h, AsyncUdpSocket.m 文件拷贝到自己的project中。
然后在项目中添加CFNetwork.framework工具包。
然后开始创建连接,代码如下:
scoket=[[AsyncSocket alloc]initWithDelegate:self]; //初始化
[scoket connectToHost:@"host端口" onPort:port error:nil];
//例如:
[scoket connectToHost:@"192.168.10.128" onPort:4001 error:nil];
连接的具体步骤点击connectToHost即可查看。
创建连接后,导入代理标题头@interface ViewController ()<AsyncSocketDelegate>使用下边代理方法:
代理方法1:查看scoket是否连接成功
-(void)onSocket:(AsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port{
NSLog(@"连接成功");
[scoket readDataWithTimeout:timezone tag:1];//接收数据
//心跳包
_connectTimer=[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(longConnectToScoket) userInfo:nil repeats:YES];
}
longConnectToScoket方法的实现如下:
//心跳包长连接
-(void)longConnectToScoket{
[scoket readDataWithTimeout:timezone tag:1];//接收数据
}
接下来是数据的封装、发送与接收:
-(void)clickPublish{
[email protected]{
@"user" :@"linda", //用户名
@"museum" :@"1", //博物馆名
@"content" :commentField.text //评论内容
};
//字典转换成字符串
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:nil];
str=[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
//封装数据
NSData *commentData=[str dataUsingEncoding:NSUTF8StringEncoding];
[scoket writeData:commentData withTimeout:10 tag:1];//发送数据
[scoket readDataWithTimeout:30 tag:1];//接收数据
commentField.text=nil;//清空评论栏内容
}
对获取的数据进行处理:
-(void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag{
NSLog(@"data:%@",data);
NSString *message=[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"message:%@",message);
//把字符串转化字典
NSData *jsonData = [message dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *dic1=[NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];
str1=[dic1 objectForKey:@"content"];//获取键所对应的值
NSLog(@"str1=%@",str1);
//发出通知
[[NSNotificationCenter defaultCenter]postNotificationName:@"change" object:str1];
}
//通知接收,其中_allComments是可变数组
-(void)receiveNotify{
//注册通知
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(message:) name:@"change" object:nil];
}
//注册通知方法
-(void)message:(NSNotification *)note{
NSString *str=[[NSString alloc]init];
str = note.object;
_allComments=[[NSMutableArray alloc]init];
[_allComments addObject:str];
[self start];
}