iOS-解决GCDAsyncSocket使用中夹杂\r\n与字节流问题

在对接某音乐协议时,遇到的问题,其中音乐协议参考:Java-解决音乐协议中的Socket通信字节传输问题

首先,需要读取\r\n前的Header,需要使用:

[_dataSocket readDataToData:[GCDAsyncSocket CRLFData] withTimeout:-1 tag:DATA_HEADER];

不能直接使用:

[_dataSocket readDataWithTimeout:-1 tag:DATA_HEADER];

否则与后面读取字节流混杂使用时,会出现数据读取错乱:

[_dataSocket readDataToLength:length withTimeout:-1 tag:DATA_CONTENT];

完整代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
- (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
{
if(tag == DATA_HEADER){
NSLog(@"TCP Package Header:%@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
NSDictionary *header = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
NSDictionary *pcmData = [header objectForKey:@"PCMData"];
_lastHeader = header;
int length = [[pcmData objectForKey:@"Length"] intValue];
[_dataSocket readDataToLength:length withTimeout:-1 tag:DATA_CONTENT];
}else if(tag == DATA_CONTENT){
NSLog(@"TCP Package Content:%ld", data.length);
[self onResponse:_lastHeader data:data tag:DATA];
[_dataSocket readDataToData:[GCDAsyncSocket CRLFData] withTimeout:-1 tag:DATA_HEADER];
[_dataSocket readDataWithTimeout:-1 tag:DATA_HEADER];
}
}