我正在用 c (winsock2) 编写一个非常简单的网络服务器。
我能够返回我的 html 页面的内容。
目前,我正在做的是将文件内容写入 char* 缓冲区并使用“send()”发送
尽管当我尝试读取图像(jpg,bmp)时,我无法将字符写入缓冲区,因为某些字符是“null”(0)。
如何发送整个图像文件?
谢谢。
我正在用 c (winsock2) 编写一个非常简单的网络服务器。
我能够返回我的 html 页面的内容。
目前,我正在做的是将文件内容写入 char* 缓冲区并使用“send()”发送
尽管当我尝试读取图像(jpg,bmp)时,我无法将字符写入缓冲区,因为某些字符是“null”(0)。
如何发送整个图像文件?
谢谢。
您需要了解 send() 和 fread() 的工作原理。缓冲区中的 0 对 send 或 fread 来说不是问题——它们不会将缓冲区解释为以 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;
}
}
}
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