简体   繁体   中英

how to send an image in winsock2, using c

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.

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;
        }
    }
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM