使用socket over http发送结构

时间:2015-10-26 03:40:23

标签: c sockets http

我想使用send()和recv()通过http传输结构(包含数据和ID等)。通过TCP,以下两行完美地运行。

Client: send(sock, (char *)&StructToSend, sizeof(StructToSend), 0);
Server: recv(sock, (char *)&StructToRecv,  sizeof(StructToRecv),0); 

但是当通过HTTP时,StructToRecv只获得两个字节的乱码:ÈÈ

    ////Client code: send over http
    int length = 0;
    char header[4096];
    char tmp_name[80];
    memset(tmp_name, 0, sizeof(tmp_name));
    strcat_s(tmp_name, "tmp.txt");

    length  = (sizeof(SendStruct)+strlen(tmp_name)+ 287);

    sprintf_s(header, "POST /%s/index.html HTTP/1.1\r\n", sub_dir;
    sprintf_s(header, "%sHost: %s \r\n", header , szIP);
    sprintf_s(header, "%sUser-Agent: Mozilla/5.0 (Windows NT 6.1; rv:32.0) Gecko/20100101 Firefox/32.0\r\n", header);
    sprintf_s(header, "%sAccept: text/html;q=0.9,*/*;q=0.8\r\n", header);
    sprintf_s(header, "%sAccept-Language: en-US,en;q=0.5\r\n", header);
    sprintf_s(header, "%sAccept-Encoding: gzip, deflate\r\n", header);
    sprintf_s(header, "%sConnection: Keep-Alive\r\n", header);
    sprintf_s(header, "%sContent-Type: multipart/form-data; boundary=-----------------------------26774670897926\r\n", header);
    sprintf_s(header, "%sContent-Length: %d\r\n", header, length );
    sprintf_s(header, "%s\r\n", header);  //blank line
    sprintf_s(header, "%s-------------------------------26774670897926\r\n", header);
    sprintf_s(header, "%sContent-Disposition: form-data; name=\"file\"; filename=\"%s\"\r\n", header, tmp_name);
    sprintf_s(header, "%sContent-Type: text/plain\r\n", header);
    sprintf_s(header, "%s\r\n", header);  //blank line
    sprintf_s(header, "%s%s\r\n", header,  (char *)&StructToSend );
    sprintf_s(header, "%s-------------------------------26774670897926\r\n", header);
    sprintf_s(header, "%sContent-Disposition: form-data; name=\"submit\"\r\n", header);
    sprintf_s(header, "%s\r\n", header);
    sprintf_s(header, "%sSubmit\r\n\r\n", header);
    sprintf_s(header, "%s-------------------------------26774670897926--\r\n\r\n\0", header);      

    send(sock, header, sizeof(header), 0);


    ////Server code : recv over http 
    char http_data[4096] = { '\0' };
    ZeroMemory( http_data, sizeof( http_data));
    recv(sock,  http_data,  4096, 0);

1 个答案:

答案 0 :(得分:3)

sprintf_s(header, "%s%s\r\n", header,  (char *)&StructToSend );

您正在使用sprintf(...%s..)。这意味着您提供的数据被视为以\0终止的字符串,即仅包含第一个\0的数据。