Question

I am writing a very simple webserver in c (winsock2).

I am able to return the contents of my html pages.

Currently, what I am doing is writing the contents of a file into a char* buffer and sending it using "send()"

Although when I try to read an image (jpg, bmp), I can't write the characters into a buffer a some characters are "null" (0).

How can I send a whole image file ?

Thanks.

Was it helpful?

Solution

You can store null character in a char* buffer. You just have to use a counter to remember how many characters were written, instead of recomputing it by counting number of non-null characters (this can either be an integer or a pointer to the next point of insertion in the buffer).

To send a file, you'll do something like that:

int sendFile(int sock, const char* filename) {
    FILE* file = fopen(filename, "rb");
    if (file == NULL)
        return -1;

    if (fseek(file, 0, SEEK_END) != 0) {
        fclose(file);
        return -1;
    }

    off_t size = ftello(file);
    if (fseek(file, 0, SEEK_SET) != 0) {
        fclose(file);
        return -1;
    }

    if (SendBinaryFileHeaderAndSize(sock, size) < 0) {
        fclose(file);
        return -1;
    }

    char buffer[4096];
    for (;;) {
        size_t read = fread(buffer, 1, sizeof(buffer), file);
        if (read == 0) {
            int retcode = 0;
            if (ferror(file))
                retcode = -1;
            fclose(file);
            return retcode;
        }

        for (size_t sent = 0; sent < read;) {
            int ret = send(sock, buffer + sent, read - sent, 0);
            if (ret < 0) {
                fclose(file);
                return -1;
            }

            assert(ret <= read - sent);
            sent += ret;
        }
    }
}

OTHER TIPS

You need to understand how send() and fread() work. 0s in the buffer are not a problem for send or fread - they do not interpret their buffers as null-terminated strings.

Depending on how you load the image into your webserver, you would need to use either Winsock:TransmitPackets or Winsock:TransmitFile, also also wrapping the image in the appropriate HTTP headers

Note that these are MS specific extensions.

Also see c++ - Bitmap transfer using winsock getdibits and setdibits

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top