c - 通过流套接字发送图像

标签 c sockets tcp transactions

谁能告诉我是否有一种通过 tcp 套接字发送图像(特别是 .jpeg 文件)的特殊方法?到目前为止,我正在开发一个似乎可以很好地发送所有文本数据的网络服务器。当涉及到 jpeg 图像时,会发送 header ,但是,Cygwin 控制台在发送实际数据时会卡住。

我发送数据的方式是首先打开文件,将数据读入缓冲区,然后将其推送。有什么建议吗?

    while(!feof(sendFile)){

            bzero(send_buffer,sizeof(send_buffer));
            result = fread (send_buffer,1,sizeof(send_buffer),sendFile);

            while(result>0){
                result = fread (send_buffer,1,sizeof(send_buffer),sendFile);

                if(ferror(sendFile)){
                    printf("Error reading file: %s\n",request_page);
                }
                if((test=send(new_fd,send_buffer,sizeof(send_buffer),0))<0){
                    printf("Send returned %d\n",test);
                    printf("Sending %s Failed\n", request_page);
                    exit(1);
                }
                bzero(send_buffer,sizeof(send_buffer));
            }
        }
        fclose(sendFile);

最佳答案

此代码有几处错误或潜在错误。

result = fread (send_buffer,1,Fsize,sendFile);

此行从 sendFile 读取 Fsize 字节到 send_buffer。现在,我在这里看不到您从哪里获得 Fsize,但鉴于它的名称,我猜它是文件的大小。您是否确保 send_buffer 足够大以容纳 Fsize 字节?否则,您可能会在此处发生缓冲区溢出,这可能会导致随机数据写入您的堆栈,从而导致各种麻烦。您可能想读入 sizeof(send_buffer)。您在这里似乎也有一个常量,MAX_MSG。那等于发送缓冲区的大小吗?如果不是,那条线也会有问题。通常,您应该尝试使用一种一致的方法来引用此缓冲区的大小,这样您就不会被两个不同的值弄糊涂而导致问题。

接下来,您尝试测试读取文件的错误:

if(result != Fsize && (result!=0)) {
printf("Reading error"); 
exit (1);
}

现在,让我们看看documentation是什么对于 fread 说:

fread() and fwrite() return the number of items successfully read or written (i.e., not the number of characters). If an error occurs, or the end-of-file is reached, the return value is a short item count (or zero).

fread() does not distinguish between end-of-file and error, and callers must use feof(3) and ferror(3) to determine which occurred.

在这里,如果您没有完全 Fsize 或零项,则会抛出错误。现在,根据文档,在错误或文件结束的情况下,您的计数可能会很短或为零。要区分您是需要提前退出循环,还是因为错误而死,您需要调用 feof 和/或 ferror

我猜你的错误在于上面提到的缓冲区溢出,但我建议同时解决这两个问题。

关于c - 通过流套接字发送图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3689859/

相关文章:

c++ - IO 完成端口和套接字 WSARecv()

c++ - 连接非 IOCP 客户端与 IOCP 服务器

c - 如何连接到 c 中的 bit torrent tracker

c - 使用 select() 的 TCP 服务器

Java TCP 心跳无法正常工作

c# - 通过最小转置数生成所有排列 C -> C#

编译器在包含其他库后不接受外部变量

bash - bash :保持连接活跃

c - Alsa,无法连续播放同一轨道两次

c - 函数中的段错误