我的游戏中有一个枚举。带有附加 PacketType 的简单字符串消息正在通过 GameKit WIFI 连接与消息一起发送(因此它知道如何处理消息)。我使用 Apple 的 GKRocket 示例代码作为起点。
代码本身运行良好;我只想了解带有 CFSwapInt32HostToBig
的行在做什么。 那到底是做什么用的?为什么需要这样做?我的猜测是它确保 PacketType 值可以转换为无符号整数,以便它可以可靠地发送它,但这对我来说听起来不太正确。
文档指出“将 32 位整数从大端格式转换为主机的 native 字节顺序。”但我不明白这到底意味着什么。
typedef enum {
PacketTypeStart, // packet to notify games to start
PacketTypeRequestSetup, // server wants client info
PacketTypeSetup, // send client info to server
PacketTypeSetupComplete, // round trip made for completion
PacketTypeTurn, // packet to notify game that a turn is up
PacketTypeRoll, // packet to send roll to players
PacketTypeEnd // packet to end game
} PacketType;
// ....
- (void)sendPacket:(NSData *)data ofType:(PacketType)type
{
NSLog(@"sendPacket:ofType(%d)", type);
// create the data with enough space for a uint
NSMutableData *newPacket = [NSMutableData dataWithCapacity:([data length]+sizeof(uint32_t))];
// Data is prefixed with the PacketType so the peer knows what to do with it.
uint32_t swappedType = CFSwapInt32HostToBig((uint32_t)type);
// add uint to data
[newPacket appendBytes:&swappedType length:sizeof(uint32_t)];
// add the rest of the data
[newPacket appendData:data];
// Send data checking for success or failure
NSError *error;
BOOL didSend = [_gkSession sendDataToAllPeers:newPacket withDataMode:GKSendDataReliable error:&error];
if (!didSend)
{
NSLog(@"error in sendDataToPeers: %@", [error localizedDescription]);
}
}
最佳答案
网络数据是大端。客户端可能是大端(例如 PowerPC Mac)或小端(例如 x86 Mac)。因此,您的代码确保字节顺序在小端平台(例如 x86)上得到处理 - 当然,它在大端系统上是无操作的。
关于c - 了解字节顺序和函数,如 CFSwapInt32HostToBig,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3051267/