在GCDAsyncSocket中通过TCP传输文件

时间:2013-11-27 22:38:11

标签: ios objective-c tcp file-transfer gcdasyncsocket

我正在编写一个游戏,我打算将.caf声音文件从iPhone传输到我的C ++服务器。现在,当我发送sendGameUpdateWithFile函数时,我得到一个 EXC_BAD_ACCESS ,我真的不知道为什么。

虽然这与任何单一作业无关,但请记住,我是CS学生,而不是(还)专业网络程序员,所以此后判断我的代码。

这是我用来将数据传输到服务器的代码(现在崩溃了):

- (void) sendGameUpdateWithFile:(NSString*)filePath gameID:(NSInteger)gameID {
    NSMutableData* data = [[NSMutableData alloc] init];
    data = [NSMutableData dataWithContentsOfFile:filePath];

    fileheadPacket head;

    head.msgtype = 0x12;
    strncpy(head.data1, [myUsername cStringUsingEncoding:NSASCIIStringEncoding], [myUsername length]);
    int followingPackets = (([data length] % 1024 == 0) || ([data length] < 1024))? ([data length]/1024) : ([data length]/1024)+1;
    head.following = followingPackets;
    head.fileid = gameID;
    head.size = sizeof(packet);

    [mySock writeData:[NSData dataWithBytes:&head length:sizeof(packet)] withTimeout:-1 tag:7];

    filePacket sendPackets[followingPackets];

    for(int i = 0; i < followingPackets; i++){
        NSRange thisRange;
        thisRange.location = i*1024;
        thisRange.length = (i+1)*1024;

        filePacket tmp;
        tmp.msgtype = 0x13;
        tmp.size = sizeof(filePacket);
        memset(tmp.data1, 0, sizeof(tmp.data1));
        [data getBytes:tmp.fileBuffer range:thisRange];

        strncpy((char*)&sendPackets[i], (char*)&tmp, sizeof(tmp));
    }

    for(int i = 0; i < followingPackets; i++){
        [mySock writeData:[NSData dataWithBytes:&sendPackets[i] length:sizeof(filePacket)] withTimeout:-1 tag:3];
    }
}

我用于数据的结构如下所示:

typedef struct file_packet {
    int msgtype:8;
    int size:16;
    int nul:8;
    int following:24;
    int emp:8;
    char data1[64];
    char fileBuffer[1024];
} filePacket;

typedef struct filehead_packet {
    int msgtype:8;
    int size:16;
    int nul:8;
    int following:24;
    int emp:8;
    char data1[64];
    int fileid;
    char rest[60];
} fileheadPacket;

服务器期望给定的msgtypes - 问题在于客户端。

任何帮助都将非常感谢!提前谢谢。

0 个答案:

没有答案