Ok这是问题所在。我试图通过苹果蓝牙发送网络数据包代码通过结构或任何东西发送。要发送的代码在
之下-(void)sendMessagePacket:(GKSession *)session packetID:(int)packetID withData:(void *)data ofLength:(int)length reliable:(BOOL)howtosend {
static unsigned char networkPacket[maxPacketSize];
const unsigned int packetHeaderSize = 2 * sizeof(int); // we have two "ints" for our header
if(length < (maxPacketSize - packetHeaderSize)) { // our networkPacket buffer size minus the size of the header info
int *pIntData = (int *)&networkPacket[0];
// header info
pIntData[0] = 10;
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) {
[session sendDataToAllPeers:packet withDataMode:GKSendDataReliable error:nil];
} else {
[session sendDataToAllPeers:packet withDataMode:GKSendDataUnreliable error:nil];
}
}
}
如果有人可以用梳子来解决这个问题并解释发生了什么,那将非常感激。接下来是接收代码。
- (void)receiveData:(NSData *)data fromPeer:(NSString *)peer inSession: (GKSession *)session context:(void *)context {
// Caller whenever data is received from the session
unsigned char *incomingPacket = (unsigned char *)[data bytes];
//EXPECTS THAT WHAT IS IN INCOMING PACKET [0] TO BE OF DATA TYPE INTEGER
int *pIntData = (int *)&incomingPacket[0];
int packetTime = pIntData[0];
int packetID = pIntData[1];
static int lastPacketTime = -1;
switch (packetID) {
case NETWORK_COINTOSS:
//DO SOMETHING
break;
case NETWORK_TEXT_EVENT:
NSString *fewMore = (NSString *)&incomingPacket[8];
fewThings *bitMore = &fewMore[peer];
//NSLog(@"Trace Bit More: %@",fewMore);
break;
default:
break;
}
NSInteger lengthBytes = [data length];
NSLog(@"Length of data : %i", lengthBytes);
}
我正在努力使其成为目标c的新成员是这一切是如何工作的,我如何访问我发送的字符串,因为所有记录它的努力都会导致程序崩溃。
以下是用于开始发送的代码:
NSString *bigWord = @"BigWordBigWord";
NSInteger len = [bigWord length];
[self sendMessagePacket:gameSession packetID:NETWORK_TEXT_EVENT withData:bigWord ofLength:(len) reliable:YES];
任何帮助都会非常感激。谢谢。
答案 0 :(得分:1)
您确实需要将NSString对象更改为要发送的UTF8表示形式,或将其存档为您使用全长发送的NSData对象 - 您不能只将NSString转换为C字符串(用于发送)或接收!!!)。
您可以使用以下命令获取NSString的C字符串版本:
const char * sendString = [bigWord cStringUsingEncoding:NSUTF8StringEncoding]
然后使用
将其从传入的NSData对象中删除NSString *result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
答案 1 :(得分:0)
这家伙正在通过网络发送和接收字符串就好了。但是,我在接收端仍然会收到错误。
http://discussions.apple.com/thread.jspa?messageID=10215848
终于明白了。 GKTank使用struct传输数据,所以我将我的字符串放在struct中,rest是历史记录。
typedef struct {
NSString *strInfo;
} myInfo;