我为移动定义了一个结构
typedef struct {
MsgType msgType;
int newFallenStonesSize;
char *newFallenStones;
} MsgMove;
并发送如下数据:
MsgMove message;
message.msgType = MsgTypeMove;
message.newFallenStones = (char *)malloc(nrNewFallenStones*sizeof(char));
for (int i=0; i<nrNewFallenStones; i++) {
message.newFallenStones[i]=newFallenStones[i];
}
message.newFallenStonesSize = nrNewFallenStones;
NSData *data = [NSData dataWithBytes:&message length:(2*sizeof(int)+message.newFallenStonesSize*sizeof(char))];
[[KKGameKitHelper sharedGameKitHelper] sendDataToAllPlayers:data reliable:YES];
发送时数据是正确的,但是当我收到这样的数据时:
else if (msg->msgType == MsgTypeMove)
{
MsgMove *msgMove = (MsgMove *) [data bytes];
for (int i=0; i<msgMove->newFallenStonesSize; i++) {
NSLog(@"New Stone received:%i",msgMove->newFallenStones[i]);
}
}
价值观发生了变化。例如,1,6,3和我收到76,105 98。
任何人都知道为什么会这样?
答案 0 :(得分:2)
主要问题是您通过网络发送指向数据的指针而不是实际数据。当您为message.newFallenStones
设置malloc空间时,它将被设置为内存中与您的MsgMove
结构不相邻的一些明显随机的位置。然后,将数据写入此其他内存位置。你打包传输的是MsgMove结构(带有指向内存中其他地方的指针)以及在内存中紧跟其后发生的任何随机字节。
处理这种方法的典型方法是将整个消息拼接在一起并将数据写入其末尾。更像是:
typedef struct {
MsgType msgType;
int newFallenStonesSize;
char newFallenStones; // The first newFallenStones value
} MsgMove;
然后发送
MsgMove *message;
message = (MsgMove *)malloc(sizeof(MsgMove)+nrNewFallenStones-1);
message->msgType = MsgTypeMove;
message->newFallenStonesSize = nrNewFallenStones;
char *newStones = &MsgMove->newFallenStones;
for (int i=0; i<nrNewFallenStones; i++) {
newStones[i]=newFallenStones[i];
}
NSData *data = [NSData dataWithBytes:message length:(sizeof(MsgMove)+nrNewFallenStones-1)];
[[KKGameKitHelper sharedGameKitHelper] sendDataToAllPlayers:data reliable:YES];