[英]how to send an image in winsock2, using c
I am writing a very simple webserver in c (winsock2). 我在c(winsock2)中写了一个非常简单的网络服务器。
I am able to return the contents of my html pages. 我能够返回我的html页面的内容。
Currently, what I am doing is writing the contents of a file into a char* buffer and sending it using "send()" 目前,我正在做的是将文件的内容写入char *缓冲区并使用“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). 虽然当我尝试读取图像(jpg,bmp)时,我无法将字符写入缓冲区,但某些字符为“null”(0)。
How can I send a whole image file ? 如何发送整个图像文件?
Thanks. 谢谢。
You can store null character in a char*
buffer. 您可以在
char*
缓冲区中存储空字符。 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. 您需要了解send()和fread()的工作原理。 0s in the buffer are not a problem for send or fread - they do not interpret their buffers as null-terminated strings.
缓冲区中的0不是send或fread的问题 - 它们不会将它们的缓冲区解释为以null结尾的字符串。
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 根据您将图像加载到Web服务器的方式,您需要使用Winsock:TransmitPackets或Winsock:TransmitFile ,还要将图像包装在适当的HTTP头中
Note that these are MS specific extensions. 请注意,这些是特定于MS的扩展。
Also see c++ - Bitmap transfer using winsock getdibits and setdibits 另请参阅c ++ - 使用winsock getdibits和setdibits进行位图传输
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.