/*
typedef struct NetStruct_twoData
{
int header;//包頭
int length;//包總長(zhǎng)度
int cmd;//信號(hào)令
int num;//數(shù)據(jù)條數(shù)
int dataNum;//字段數(shù)
int dataType_one;//字段類型
int dataType_two;//字段類型
int dataLength_one;//字段長(zhǎng)度
int dataLength_two;//字段長(zhǎng)度
int data[50];//字段
Byte verify;//校驗(yàn)
Byte version;//版本號(hào)
int tail;//包尾
*/
事例代碼(發(fā)送一個(gè)心跳包):
- (NSData*)heartBeat
{
unsigned int header = 0x12345678;
unsigned int length = (unsigned int)(8*4+2+4);
unsigned int cmd = 0x00000000;
unsigned int num = 0x00000001;
unsigned int datanum = 0x00000001;
unsigned int dataType_one = 0x00000002;
unsigned int dataLength_one = 4;
// 大小端轉(zhuǎn)換
header = CFSwapInt32BigToHost(header);
length = CFSwapInt32BigToHost(length);
cmd = CFSwapInt32BigToHost(cmd);
num = CFSwapInt32BigToHost(num);
datanum = CFSwapInt32BigToHost(datanum);
dataType_one = CFSwapInt32BigToHost(dataType_one);
dataLength_one = CFSwapInt32BigToHost(dataLength_one);
NSMutableData * contentData = [[NSMutableData alloc]init];
[contentData appendBytes:&header length:4];
[contentData appendBytes:&length length:4];
[contentData appendBytes:&cmd length:4];
[contentData appendBytes:&num length:4];
[contentData appendBytes:&datanum length:4];
[contentData appendBytes:&dataType_one length:4];
[contentData appendBytes:&dataLength_one length:4];
[contentData appendBytes:"abcdefghui" length:4];
Byte * dataString = (Byte *)[contentData bytes];
Byte eox;
memcpy(&eox, dataString, 1);
for (NSUInteger i = 1 ; i < contentData.length; i ++) {
eox = eox^dataString[i];
}
[contentData appendBytes:&eox length:1];
unsigned int version = 0x01;
unsigned int tail = 0x87654321;
tail = CFSwapInt32BigToHost(tail);
[contentData appendBytes:&version length:1];
[contentData appendBytes:&tail length:4];
return contentData;
}
具體調(diào)用代碼:
結(jié)合第三方的GCDAsyncSocket開源代碼,保持心跳包
GCDAsyncSocket * _sendSocket;
//創(chuàng)建一個(gè)后臺(tái)隊(duì)列等待接受數(shù)據(jù)
dispatch_queue_t dQueue = dispatch_queue_create("socket queue", NULL);
if (_sendSocket == nil) {
_sendSocket = [[GCDAsyncSocket alloc]initWithDelegate:self delegateQueue:dQueue socketQueue:nil];
}
[_sendSocket writeData:data withTimeout:-1 tag:10];