如何使用C中的Winsock2发送图像
-
25-10-2019 - |
题
我在C(winsock2)中写了一个非常简单的Web服务器。
我能够返回HTML页面的内容。
目前,我正在做的是将文件内容写入char*缓冲区,并使用“ send()”发送它。
尽管当我尝试阅读图像(JPG,BMP)时,我无法将字符写入缓冲区中,某些字符是“ null”(0)。
如何发送整个图像文件?
谢谢。
解决方案
您可以将null字符存储在 char*
缓冲。您只需要使用计数器来记住写了多少个字符,而不是通过计算非挂钩字符的数量来重新计算它(这可以是整数或指向缓冲区中下一个插入点的指针)。
要发送文件,您将做类似的事情:
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;
}
}
}
其他提示
您需要了解send()和fread()工作方式。缓冲区中的0不是发送或frad的问题 - 它们不会将其缓冲区解释为无效的终止字符串。
根据您将图像加载到网络服务器中的方式,您都需要使用 Winsock:Transmitpackets 或者 Winsock:TransMitfile, ,也将图像包裹在适当的HTTP标头中
请注意,这些是MS特定的扩展。
不隶属于 StackOverflow