c - 从套接字读取/写入意外行为

标签 c sockets

我有一个任务,我必须从服务器下载一个文件..但我有这样的情况,有时数据被发送,有时却没有!

服务器:

printf("Reading and sending the File.\n");
memset(buff, 0, sizeof(buff));
while((n=read(fp, buff, 1024)) > 0 )
{   
    printf ("%s \n", buff); //no problem, coz it reads the file correctly  
    write(connfd, buff, n); 
    memset(buff, 0, sizeof(buff));
}

客户:

printf("Start downloading the file.\n");
bzero(&data,sizeof(data));
n = 0;
while (1)
{
    n = read(sockfd , data, 1024);
    if (n > 0)
    {
         data[n] = 0;
         r = write (fp, data, n);
         if (r < 0)
         {
             printf("Write to file !!!!!!\n");
         exit(1);
         }
    }
    printf ("\n%s\n", data);
    bzero (&data, sizeof (data));
    if (n < 1024)
        break;
}
printf("Done downloading the file\n");
close (fp);

最佳答案

由于实现原因(套接字、TCP 堆栈、以太网堆栈等),即使发送了这么多字节,您也可能无法在每次读取中始终获得 1024 字节。

您正在使用if (n < 1024)检查您是否完成。这不应该用套接字来完成。

首先您需要更改readrecv它是专门为与套接字配合使用而设计的。 recv将返回0如果服务器已有序关闭连接并且 -1如果发生错误。任何其他返回值都意味着:继续阅读!

printf("Start downloading the file.\n");
ssize_t n;
while (1)
{
    n = recv(sockfd, data, sizeof(data), 0);
    if (n > 0)
    {
         r = write (fp, data, n);
         if (r < 0)
         {
            perror("write");
            exit(1);
         }

        printf ("\n%*s\n", n, data);
    }
    else if (!n)
        break; // orderly shutdown
    else {
        perror("recv");
        exit(1);
    }
}
printf("Done downloading the file\n");
close (fp);

关于c - 从套接字读取/写入意外行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19637963/

相关文章:

C 代码测量 Linux 中的磁盘写入时间并处理 RAM 缓冲

c - 没有回调的 Nanopb

c - 从 fgets() 输入中删除尾随换行符

网络崩溃和套接字的后续状态

c - 在客户端-服务器应用程序 (UDP) 中创建并发服务器时出现错误的文件描述符错误

c - 在 C 中使用 read() 从 stdin 读取

c - 通过引用传递结构? [C]

java - Arduino Client通过Sockets向Java Server发送数据

java - 如何针对 Java 客户端实现 C++ 套接字服务器?

java - 无法从 AsyncTask 和无限循环更新 EditText