安卓跟iOS通讯的时候,你会发现你接到对方发的json串解析不了,对,因为安卓在发送json的时候,安卓默认的在数据的Byte前两位加上了data总长度,所以我们在解析的时候要先把接收到数据的前两位解析出需要接受数据的大小长度。然后我们就知道这段data只接收解析出长度的大小。防止数据错乱!
还是上代码
/**
*解析Json
*
*@param client_NeedFD客户端标识FD
*
*@return Json格式字符串
*/
- (NSString*)RecognizeDataWithClientFD:(int)client_NeedFD{
NSString*needReturnIn =nil;
charbuf[1024];
intallLength =0;
intbits =0;
NSInteger br;
//判断是否是第一次1.第一次判断前两位长度
BOOLisFirst =YES;
NSMutableData*mutableData = [[NSMutableDataalloc]init];
while((br =recv(client_NeedFD, buf,1024,0))!=-1) {//接受的长度
//取到所有json
allLength +=br;
NSData*headData = [[NSDataalloc]initWithBytes:buflength:br];
[mutableDataappendData:headData];
if(isFirst) {
bits = [selfbytes_to_IntWithData:headDataLength:0];//应该接受的长度
isFirst =NO;
}
//1.如果已经接收的总长度allLehgth小于应该接收的长度Bits继续接收
//2.否则break跳出该循环
//NSLog(@"allLength = %dbr = %d收到左右的JSON Break",allLength,br);
if((allLength -2) == bits) {
NSString*jsonString = [selfconvertToNSStringFromJavaUTF8:mutableDataWithLength:bits];
needReturnIn = jsonString;
break;
}
//memset(buf, 0, sizeof(buf));//总的作用:将已开辟内存空间s的首n个字节的值设为值c。函数常用于内存空间初始化
if(br ==0) {
close(client_NeedFD);
break;
}
}returnneedReturnIn;
}
- (int)bytes_to_IntWithData:(NSData*)data Length:(int)len{//取出前两位,计算出本次应该接受的长度
intvalue=0;
Byte*byte = (Byte*)[databytes];
if([datalength]>2) {//解析前两位
value = (int)(byte[1+len] &0xFF)|(byte[0+len]<<8&0xFF00);
}
returnvalue;
}
- (NSString*) convertToNSStringFromJavaUTF8 : (NSData*) data WithLength:(int)len{
intlength = (int)[datalength];
constuint8_t*bytes = (constuint8_t*)[databytes];
if(length <2) {
returnnil;
}
bytes +=2;
return[[NSStringalloc]initWithBytes:byteslength:lenencoding:NSUTF8StringEncoding];
#if0 //+2就代表从第三位开始,下面是例子,可以改变数字,自己试试
NSString *str1 =@"123456";
NSData *data1 = [str1 dataUsingEncoding:NSUTF8StringEncoding];
intlength = (int)[data1 length];
constuint8_t *bytes = (constuint8_t*)[data1 bytes];
NSString *json = [[NSString alloc] initWithBytes:bytes+2length:length-2encoding:NSUTF8StringEncoding];
XCLog(@"%@",json);
#endif
}
二、发送的时候记得也在发送的data前面加上你要发送json的长度
- (NSInteger)sendSocketWithJson:(NSString*)jsonString SockFD:(int)sock_fd{
NSData*mutableData = [[DealwithJson shareInstance]NeedJsonString:jsonString];
Byte*sendByte = (Byte*)[mutableDatabytes];
returnsend(sock_fd, sendByte, [mutableDatalength],0);
}
//下面是在bytes前面加上长度,注意bytes的高地位
- (NSData*)NeedJsonString:(NSString*)jsonStirng {
NSData*data1 = [jsonStirngdataUsingEncoding:NSUTF8StringEncoding];
#if __LP64__ || NS_BUILD_32_LIKE_64
//long sendSuccess;
NSIntegerbits = [data1length];
#else
//int sendSuccess;
intbits = [data1 length];
#endif
shortbit = bits;
NSData*data2 = [NSDatadataWithBytes:&bitlength:sizeof(bit)];//低位高位
Byte*testByte = (Byte*)[data2bytes];
/**
*修改byte高地位--适应安卓
*/
intone = testByte[0];
testByte[0] = testByte[1];
testByte[1] = one;
NSData*data3 = [[NSDataalloc]initWithBytes:testBytelength:2];
NSMutableData*mutableData = [[NSMutableDataalloc]initWithData:data3];//先把长度加上
[mutableDataappendData:data1];//要发出的数据
returnmutableData;
}
网友评论