Skip to content

Instantly share code, notes, and snippets.

@typeoneerror
Created May 31, 2011 22:59
Show Gist options
  • Save typeoneerror/1001461 to your computer and use it in GitHub Desktop.
Save typeoneerror/1001461 to your computer and use it in GitHub Desktop.
gamekit packets
/** Types of packets sent by session. */
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. */
PacketTypeHeartbeat, /**> packet to attempt to keep peers alive. */
PacketTypeRematch, /**> packet to send a rematch message to peers. */
PacketTypeAvatars /**> sending packet containing player images. */
} PacketType;
//////
// sends data to the connected peers
- (void)sendPacket:(NSData *)data ofType:(PacketType)type
{
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);
[newPacket appendBytes:&swappedType length:sizeof(uint32_t)];
[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);
}
}
// handles data sent to peers
- (void)receiveData:(NSData *)data fromPeer:(NSString *)peer inSession:(GKSession *)session context:(void *)context
{
PacketType header;
uint32_t swappedHeader;
if ([data length] >= sizeof(uint32_t))
{
// chop off the packet type header
[data getBytes:&swappedHeader length:sizeof(uint32_t)];
// convert it to our packet type
header = (PacketType)CFSwapInt32BigToHost(swappedHeader);
// range of data minus the packet type flag
NSRange payloadRange = {sizeof(uint32_t), [data length]-sizeof(uint32_t)};
// the data itself
NSData *payload = [data subdataWithRange:payloadRange];
// figure out the message sent
NSString *message = [[[NSString alloc] initWithData:payload encoding:NSUTF8StringEncoding] autorelease];
if (header == PacketTypeStart)
{
// do something with message
}
}
}
/////////
// using it
NSString *data = "Some string to send";
// has to be NSData
NSData *packet = [data dataUsingEncoding:NSUTF8StringEncoding];
[self sendPacket:packet ofType:PacketTypeStart]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment