谁能帮我?我使用 GCDAsyncSocket 通过 TCP 协议在两个设备之间集中交换数据。我发送这样的数据:
NSMutableDictionary *packet = [[[NSMutableDictionary alloc] init] autorelease];
[packet setObject:[NSNumber numberWithInt:MultiPlayerTypeInfoNextRoundConfirm] forKey:@"type_info"];
[packet setObject:[NSNumber numberWithBool:YES] forKey:@"connection_confirmation"];
NSMutableData *data = [[NSMutableData alloc] initWithData:[NSKeyedArchiver archivedDataWithRootObject:packet]]; //[NSKeyedArchiver archivedDataWithRootObject:packet];
if (currentGameMode == GameModeServer)
[(ServerMultiplayerManager *)multiplayerManager sendNetworkPacket:data withTag:MultiPlayerTypeInfoNextRoundConfirm];
- (void)sendNetworkPacket:(NSData *)data withTag:(long)tag
{
[asyncSocket writeData:data withTimeout:-1 tag:tag];
}
- (void)socket:(GCDAsyncSocket *)sock didWriteDataWithTag:(long)tag
{
NSLog(@"DID WRITE DATA tag is %ld", tag);
[sock readDataWithTimeout:-1 tag:0];
}
我读到这样的数据:
- (void)socket:(GCDAsyncSocket *)sender didReadData:(NSData *)data withTag:(long)tag
{
NSString *receivedInfo = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
[info_data setData:data];
NSLog(@"DID READ DATA WITH TAG %ld", tag);
if ([receivedInfo isEqualToString:ROOM_FILLED])
{
isMaster = (tcpRequest.identifier == MASTER_CHAR);
NSLog(@"IS MASTER SET %d", isMaster);
[multiplayerDelegate setGameModeServer];
[multiplayerDelegate startGame];
}
else
[self dataProcessing:info_data];
[sender readDataWithTimeout:-1 tag:0];
}
- (void)dataProcessing:(NSData *)data
{
NSDictionary *dict = [NSKeyedUnarchiver unarchiveObjectWithData:data];
MultiPlayerTypeInfo typeInfo = [[dict objectForKey:@"type_info"] intValue];
}
我的问题是这些数据包被弄乱了。假设一个标有标签 10 的数据包在接收器设备上被读取为标有标签 11 的数据包,该数据包是在数据包 10 之后立即发送的,并且在取消归档实际数据包 11 时NSKeyedUnarchiver
会抛出异常Incomprehensible archive
。
据我了解,我应该以某种方式分离数据包。我尝试将分隔符号附加到正在发送的数据中:
[data appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
并尝试像这样阅读它:
[socket readDataToData:[GCDAsyncSocket CRLFData] timeout:-1 tag:some_tag];
但这没有帮助。我做错了什么,我应该怎么做?