我在GKTank示例的结构中成功发送了int和CGPoint数据,但我拼命想要发送一个NSString。我也尝试用char而不是NSString但没有成功......
这是代码 发送:
NSString *playerName = @"My Name";
NSData *dat = [playerName dataUsingEncoding:NSUTF8StringEncoding];
[BTINconnector sendNetworkPacketwithPacketID:NETWORK_PLAYERNAME withData:dat ofLength:sizeof(dat) reliable:YES];
该方法(从GKTank获知,已修改)
- (void)sendNetworkPacketwithPacketID:(int)packetID withData:(void *)data ofLength:(int)length reliable:(BOOL)howtosend {
//NSLog(@"bmpc:ok 3 send packet to %i",gamePeerId);
// the packet we'll send is resued
static unsigned char networkPacket[kMaxPacketSize];
const unsigned int packetHeaderSize = 2 * sizeof(int); // we have two "ints" for our header
if(length < (kMaxPacketSize - packetHeaderSize)) { // our networkPacket buffer size minus the size of the header info
int *pIntData = (int *)&networkPacket[0];
// header info
pIntData[0] = gamePacketNumber++;
pIntData[1] = packetID;
// copy data in after the header
memcpy( &networkPacket[packetHeaderSize], data, length );
NSData *packet = [NSData dataWithBytes: networkPacket length: (length+8)];
if(howtosend == YES) {
[mySession sendData:packet toPeers:[NSArray arrayWithObject:gamePeerId] withDataMode:GKSendDataReliable error:nil];
} else {
[mySession sendData:packet toPeers:[NSArrayarrayWithObject:gamePeerId] withDataMode:GKSendDataUnreliable error:nil];
}
}
}
和接收方法(来自我修改的GKTank)
- (void)receiveDataDG:(NSData *)data fromPeer:(NSString *)peer inSession:(GKSession *)session context:(void *)context {
static int lastPacketTime = -1;
unsigned char *incomingPacket = (unsigned char *)[data bytes];
int *pIntData = (int *)&incomingPacket[0];
NSData* nData = (NSData*)&incomingPacket[0];
//NSData* bData = nData[8];
//
// developer check the network time and make sure packers are in order
//
int packetTime = pIntData[0];
int packetID = pIntData[1];
if(packetTime < lastPacketTime && packetID != NETWORK_COINTOSS) {
NSLog(@"bmc: EXITED");
return;
}
lastPacketTime = packetTime;
switch( packetID ) {
case NETWORK_PLAYERNAME:
{
NSData *hjk = [NSData dataWithBytes:&pIntData[2] length:sizeof(int)];
NSString *gotitb = [[NSString alloc] initWithData:hjk encoding:NSUTF8StringEncoding];
NSLog(@"bmc:str %@,%@",gotitb,gotitb);
…
gotitb返回null,但我不知道为什么。请帮忙。
答案 0 :(得分:0)
您不希望sizeof(dat)
想要[dat length]
。