1

结构:

typedef struct 
{
    NSData *levelData;
    int levelID;
} GameLevelInfo;

我如何发送数据:

    static GameLevelInfo gameLevelInfo;
    gameLevelInfo.levelData = [[LevelManager sharedManager] levelDataFromName:@"XXXXXX"]];
    gameLevelInfo.levelID = 1;
    [sendPacket:NETWORK_SENDING_LEVEL
    objectIndex:0 
           data:&gameLevelInfo 
         length:sizeof(gameLevelInfo) 
       reliable:YES];

“levelDataFromName”:

-(NSData *) levelDataFromName:(NSString *)levelName
{
    NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *filePath = [documentPath stringByAppendingFormat:@"/%@", levelName];
    return [[NSFileManager defaultManager] contentsAtPath:filePath];
}

和“sendPacket”:

- (void)sendPacket:(int)packetID objectIndex:(int)objectIndex data:(void *)data length:(int)length reliable:(bool)howtosend {

    // the packet we'll send is resued
    static unsigned char networkPacket[MAX_PACKET_SIZE];
    const unsigned int packetHeaderSize = 3 * sizeof(int); // we have two "ints" for our header 

    if(length < (MAX_PACKET_SIZE - packetHeaderSize)) { // our networkPacket buffer size minus the size of the header info
        int *pIntData = (int *)&networkPacket[0];
        // header info
        pIntData[0] = packetNumber++;
        pIntData[1] = packetID;
        pIntData[2] = objectIndex;

        // copy data in after the header
        memcpy( &networkPacket[packetHeaderSize], data, length ); 

        NSData *packet = [NSData dataWithBytes: networkPacket length: (length+packetHeaderSize)];
        if(howtosend == YES) { 
            [session sendDataToAllPeers:packet withDataMode:GKSendDataReliable error:nil];          
        } else {
            [session sendDataToAllPeers:packet withDataMode:GKSendDataUnreliable error:nil];
        }
    }
}

数据已成功发送,但在“接收方”:

GameLevelInfo *gameLevelInfo = (GameLevelInfo*)data;
NSData *content = gameLevelInfo->levelData;

“内容”是无效对象。

任何帮助将不胜感激,谢谢:)

4

0 回答 0