0

好的,这就是问题所在。我正在尝试通过苹果蓝牙发送网络数据包代码通过结构或任何东西发送。要发送的代码如下

-(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];

任何帮助将不胜感激。谢谢你。

4

2 回答 2

1

您确实需要将 NSString 对象更改为要发送的 UTF8 表示形式,或者将其归档为您发送的完整长度的 NSData 对象 - 您不能只将 NSString 转换为 C 字符串(用于发送或接收! !!)。

您可以使用以下方法获取 NSString 的 C 字符串版本:

const char *sendString = [bigWord cStringUsingEncoding:NSUTF8StringEncoding]

然后将其从传入的 NSData 对象中取出

NSString *result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
于 2009-09-15T15:35:03.970 回答
0

这家伙通过网络发送和接收字符串就好了。但是,我在接收端仍然遇到错误。

http://discussions.apple.com/thread.jspa?messageID=10215848

终于明白了。GKTank 正在使用 struct 传输数据,所以我将字符串放在 struct 中,剩下的就是历史记录。

typedef struct {
    NSString *strInfo;
} myInfo;
于 2009-11-23T16:09:41.740 回答