Search code examples
htmlc++cmongoose-web-server

How Does One Send BOTH HTML and Images Using libMongoose/Embedded Mongoose?


So the Mongoose.c library is pretty straight-forward. I've been able to use their event system, URL recognition, multi-form example, and their connection system to build a simple login-system. I've used C++ minGW, the mongoose.c&.h, and my browser. Now I'd like to implement images.

But there's a fundamental issue I can't get around. I can transfer EITHER an html document, OR an image. The jpg, alone, will display happily, as will the html document, so long as either is alone. My code is relatively simple, for html:

--pretend std::string HTMLAsString holds all html for the document.
 mg_send_data(conn,HTMLAsString,strlen(HTMLAsString));

When I want to send an image, its quite similar:

while ((fread(buf, 1, sizeof(buf), fp)) > 0) {
        mg_send_data(conn,buf,n);
}
mg_send_data(conn,"\r\n",2);

Both of these work (I've cut out the irrelevant parts like how the string is composed, or how the buffer is filled, suffice to say those aspects work). I can have HTML formatting, with a 'missing image space,' or I can have an image shown, but no HTML.

How do I send BOTH an image and HTML?


Solution

  • Mr. Andersen should get credit for this, but I can't mark a comment as an answer, and I want to close the question.

    He was dead on. First the client-browser requests the page. The server sends it. When the client-browser receives the HTML document, it then sends requests to the server for all images/files as specified in the HTML.

    I was checking all requests from clients for the addresses, using conn->uri. This allowed me to simply run string comparisons to figure out what page I was receiving data from. However, I wasn't checking for any OTHER strings apart from those I had pages for.

    As soon as I put a simple:

    std::cout << "REQUESTED:" << conn->uri << std::endl;

    I saw the requests clear as day (in my case /image.jpg). So I put the aforementioned image code together with just another string comparison in the reply function, and presto-magico, images embedded within HTML, all playing nice and happy together.

    Thank you for answering my question.

    P.S. The send file code is a little different:

    char buf[1024];
    int n;
    FILE *fp;
    fp = fopen(cstrpath, "rb");
    if(fp==NULL){printf("ERROR, NO %s found.",cstrpath);}
    while ((n = fread(buf, 1, sizeof(buf), fp)) > 0) {
        mg_send_data(conn,buf,n);
    }
    fclose(fp);
    mg_send_data(conn,"\r\n",2);