c - read() 在套接字编程中不阻塞

标签 c linux sockets network-programming

我有一个服务器,每 5 秒向客户端发送一次数据。我希望客户端在 read() 上阻塞,直到服务器发送一些数据然后打印它。我知道默认情况下 read () 是阻塞的。我的问题是我的客户没有阻塞 read()。这很奇怪,这似乎不是一个正常问题。

我的代码在无限循环中打印“Nothing came back”。我在一台linux机器上,用c编程。我的代码片段如下。请指教。

while(1)
{
    n = read(sockfd, recvline, MAXLINE);
    if ( n > 0) 
    {
        recvline[n] = 0;    
        if (fputs(recvline, stdout) == EOF)
            printf("fputs error");
    }
    else if(n == 0)
        printf("Nothing came back");
    else if (n < 0)
        printf("read error");
}
return; 

最佳答案

可能有几个原因,在不同的地方可能有几个异常(exception):

  1. 检查您创建的套接字:

    sockfd=socket(AF_INET,SOCK_STREAM,0);  
    if (sockfd==-1) {
        perror("Create socket");
    }
    
  2. 您和在使用之前显式启用阻塞模式:

    // Set the socket I/O mode: In this case FIONBIO  
    // enables or disables the blocking mode for the   
    // socket based on the numerical value of iMode.  
    // If iMode = 0, blocking is enabled;   
    // If iMode != 0, non-blocking mode is enabled.
    ioctl(sockfd, FIONBIO, &iMode);  
    

    或者您可以使用 setsockopt如下:

     struct timeval t;    
     t.tv_sec = 0;
     tv_usec = 0;
     setsockopt(
          sockfd,     // Socket descriptor
          SOL_SOCKET, // To manipulate options at the sockets API level
          SO_RCVTIMEO,// Specify the receiving or sending timeouts 
          const void *(&t), // option values
          sizeof(t) 
      );   
    
  3. 检查读取函数调用(错误原因)

    n = read(sockfd, recvline, MAXLINE);
    if(n < 0){  
        perror("Read Error:");
    }  
    
  4. 同时检查服务器代码!:

    1. May your server send some blank(non-printable, null, enter) charter(s). And your are unaware of this. Bug you server code too.

    2. Or your server terminated before your client can read.

  5. 还有一个有趣的事情,试着理解一下:

    When you call N write() at server its not necessary there should be N read() call at other side.

关于c - read() 在套接字编程中不阻塞,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12773509/

相关文章:

c - SIG_IGN, SIG_DFL, SIG_ERR 的定义

C编程: reading from file

linux - 如何从 ubuntu 11.04 中删除 java5?

c - ANSI C 如何在 Linux 中获取名称服务器 (DNS) 地址?

c - 如何对C中输出的正确名称排序列表进行排序?

c - 缓冲区管理和从串行数据中提取帧

linux - 创建 aspell 样式文件编辑 bash 脚本

c++ - 客户端套接字发送数据但服务器套接字不接收它们。 C++缓冲流?

android - 如何正确关闭套接字及其InputStream?

c++ - Unix 域套接字 : sending file descriptor and select()