【发布时间】:2021-04-10 03:37:40
【问题描述】:
我正在尝试通过sockets 将 jpg 图像从客户端进程发送到服务器。该图像包含二进制数据,因此我想使用reads 和writes 在低级编程基础上进行。我还以 100 字节的迭代发送图像数据。
这是我完成的代码,它没有按照我的意愿发送图像:
客户
void send_image(char *path, char *filename, int socket) {
int fd = open(path, O_RDONLY); //I open the file of the image.jpg
int n = 1;
while (n > 0) {
char img_data[100];
n = read(fd, img_data, 100); //sending 100 bytes of image each iteration till n=0 (end of file)
if (!n) break;
int sending = 1;
write(socket, &sending, sizeof(int)); //Tell the client the image still has data to send
write(socket, img_data, strlen(img_data));
usleep(250);
}
sending = 0; //Tell the server the image has been fully sent
write(socket, &sending, sizeof(int));
close(fd);
}
服务器
void receiving_image(char *path) {
int receiving = 0;
int j=0;
char *image_data = NULL; //Variable to store all the image data
read(socket, &receiving, sizeof(int)); //Reads that the client is going to send an image
while (receiving) {
char data[100]; //Variable that stores partial data (100 bytes) of an image on each iteration
read(socket, data, 100);
image_data = realloc(image_data, (j + strlen(data)) * sizeof(char)); //Readjust the size of the main image data.
for (int i=0; i<(int) strlen(data); i++) {
image_data[j] = data[i]; //copy the partial data of the image to the main variable of the image
j++;
}
j = (int) strlen(image_data);
read(socket, &receiving, sizeof(int)); //Read if the image is still sending
}
image_to_directory(path, image_data); //Copy image to directory
}
这编译并运行良好,但是当我检查存储图像的服务器端目录时,我可以看到它与客户端发送的图像不同(我通过 md5sum 确认并且哈希值不相等) .
我有什么遗漏吗?
【问题讨论】:
-
strlen(img_data)和strlen(data)是错误的。字符串函数只能用于字符串,不能用于二进制数据。请改用read的返回值来获取读取/接收的字节数。 -
read()在出错的情况下返回-1,而不是0。您必须测试<=0。 -
不是你的问题,因为我假设服务器和客户端在类似的机器上运行,但是
int在服务器和客户端上可以有不同的大小。最好使用uint32_t或类似的东西。 -
@12431234123412341234123 你指的是哪一行?
while (n > 0)没有做到这一点吗? -
while (n > 0)为时已晚。如果read返回-1,代码将继续并在有机会退出循环之前使用read的结果。实际引用的错误检查是if (!n)