Write a file to a socket issue

Posted on 2011-04-18
Last Modified: 2012-05-11
I am working on an HTTP response object, and have run into a problem when trying to send a file back. Everything works fine for text based files, but the moment I try to send a binary (lets say an image for example), I get garbage all over the server screen, and nothing out to the browser.

The code is attached.

Fix worth 500 points.

void Response::output (std::string out)
    //write the data to the socket
    int toSend = out.length();
    int sent = 0;

    std::cout << out;
    while (sent < toSend)
        int tmp = write(client,out.c_str(),out.length());
        sent += tmp;

void Response::httpSendFile(std::string path)
    //open a file, and transfer it as a stream
    std::ifstream myReadFile;,std::ios::binary);

    if (myReadFile.is_open())
        int begin = myReadFile.tellg();

        myReadFile.seekg (0, std::ios::end);

        int end = myReadFile.tellg();

        int lng = end - begin;

        myReadFile.seekg (0);

        int start = path.find_last_of(".");

        std::string mime = determineMimeType(path.substr(start,path.length()));

        output("HTTP/1.1 200 OK\r\n");
        //get the current date/time
        std::string now = asctime(localtime(new time_t()));
        output("Date: " + now);

        output("Server: HTTP Service 1.1\r\n");
        output("Content-Type: " + mime + "\r\n");
        if (cookie.length() > 0)
            output("Set-Cookie: " + cookie + "\r\n");

        std::stringstream length;

        length << lng;

        output("Content-Length: " +  length.str() + "\r\n\r\n");

        char tmp[4096];

        while (!myReadFile.eof())
            myReadFile >> tmp;
        sendBadHeader("404 Not Found");


Open in new window

Question by:richardsimnett
    LVL 86

    Accepted Solution

    HTTP is a text based protocol and binary data has to be base64-encoded so it can be sent using it.  See e.g. ("Encoding and decoding base64 with C++") and/or ("Base64 Encoding and Decoding")
    LVL 86

    Expert Comment

    Oh, and since it recently became common here that once an issue (here base64) was addressed with an example that other experts come forth with even more examples ("Hey, that is only slightly different, but try it anyway!") without having contributed to the original issue, we might as well cover up all other possibilites in this context:

    Author Comment

    let me ask you a question. is base 64 encoding the same as url encoding / decoding?
    LVL 86

    Expert Comment

    It looks a similar way, yet it is not the same - see
    LVL 33

    Expert Comment

    by:Todd Gerbert
    >> HTTP is a text based protocol and binary data has to be base64-encoded so it can be sent using it.

    I realize I'm a little late with this, but I think it's probably worth pointing out the above statement is wildly inaccurate, there is no reason your HTTP server can't respond with binary content, it does not need to be Base64-encoded (maybe you were thinking of SMTP).  In fact, if you telnet to on port 80 and manually type the HTTP request for the Google logo:
    GET /images/logos/ps_logo2.png HTTP/1.1

    Open in new window

    You can plainly see the web server responds with the raw, unencoded, 8-bit content of of the PNG file.

    However, you should make sure you're setting the Content-Type, Content-Length, Transfer-Encoding headers et al properly.  You also can't handle binary data internally in your application as if it were text.  Your Response::output isn't working when you select a binary file because you're trying to pass it into a std::string.  If you changed your Response::output to accept a void* and a count instead of a string (or added an overload to such effect) your code would probably work.

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    How to run any project with ease

    Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
    - Combine task lists, docs, spreadsheets, and chat in one
    - View and edit from mobile/offline
    - Cut down on emails

      Included as part of the C++ Standard Template Library (STL) is a collection of generic containers. Each of these containers serves a different purpose and has different pros and cons. It is often difficult to decide which container to use and …
    Introduction This article is a continuation of the C/C++ Visual Studio Express debugger series. Part 1 provided a quick start guide in using the debugger. Part 2 focused on additional topics in breakpoints. As your assignments become a little more …
    The goal of the video will be to teach the user the concept of local variables and scope. An example of a locally defined variable will be given as well as an explanation of what scope is in C++. The local variable and concept of scope will be relat…
    The viewer will learn how to user default arguments when defining functions. This method of defining functions will be contrasted with the non-default-argument of defining functions.

    761 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    11 Experts available now in Live!

    Get 1:1 Help Now