Home  >  Q&A  >  body text

c++和socket问题

我用socket做简单一个静态web服务器
浏览器请求html文本没有问题,
就是请求图片有了写困惑
下面是代码


            hdrFmt =
            "HTTP/1.0 200 OK\r\n"
            "Server: MySocket Server\r\n"
            "Content-Type: image/jpeg\r\n"
            "cahrset: utf-8\r\n"
            "Accept-Ranges: bytes\r\n"
            "Content-Length: %d\r\n\r\n\0";
            sprintf(headers, hdrFmt.data(),1024);
            send(csock, headers, strlen(headers), 0);
            fstream rfile;
            fstream wfile;
            char databuf[1024];
            rfile.open("test.jpg", ios::out  | ios::in  | ios::binary);
            wfile.open ("wfile.jpg", ios::out  | ios::binary | ios::trunc);
            while(rfile.is_open())
            {
                memset(databuf,0,sizeof(databuf));
                rfile.read(databuf,sizeof(databuf)-1);
                int readLen = rfile.gcount();
                wfile.write(databuf, readLen);
                send(csock, databuf, readLen, 0);//
                if(rfile.eof())
                    break;
            }
            rfile.close();
            wfile.close();
            return ;

是读取图片之后一边写入另一个图片里,一边发送socket(socket是测试通过的,能发文本)
可是效果是这样的

只发送了一部分
而写入的另一个图片是正常的

代码是一边写入一边发送的,为什么结果不一样的?
大神们看一下

PHPzPHPz2714 days ago551

reply all(2)I'll reply

  • 高洛峰

    高洛峰2017-04-17 13:51:37

    Content-Length you wrote a damn 1024, it should be the length of the content (size of the image)

    Even if you send it multiple times, Content-Length is still the total size of the image, not the size of each send

    And why not send it directly after reading it? Do you want to write to another file? Such strange logic? ?
    Is this what C++ is like? It can't be that disgusting, right?

    PS: The word is misspelled cahrset -》charset
    PS: How to manually fake the hdrFmt string 0??

    reply
    0
  • 黄舟

    黄舟2017-04-17 13:51:37

    This is not a socket problem, but a http protocol problem. Writing http in C++ is a problem that makes you feel uncomfortable.

    reply
    0
  • Cancelreply