本文是基於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{
dic=@{
@"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];
}
