Mat*_*hew 8 c sockets linux network-programming
我有一台服务器,每隔5秒就会向客户端发送一次数据.我希望客户端阻止read()直到服务器发送一些数据然后打印它.我知道read()默认是阻塞的.我的问题是我的客户端没有阻塞read().这很奇怪,这似乎不是一个正常的问题.
我的代码在无限循环中打印出"Nothing come 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; 
Run Code Online (Sandbox Code Playgroud)
    可能有几个原因,在不同的地方有几个例外:
检查您创建的套接字:
Run Code Online (Sandbox Code Playgroud)sockfd=socket(AF_INET,SOCK_STREAM,0); if (sockfd==-1) { perror("Create socket"); }
您还可以在使用前明确启用阻止模式:
Run Code Online (Sandbox Code Playgroud)// 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) 
  );   
Run Code Online (Sandbox Code Playgroud)检查读取函数调用(错误原因)
Run Code Online (Sandbox Code Playgroud)n = read(sockfd, recvline, MAXLINE); if(n < 0){ perror("Read Error:"); }
还要检查服务器代码!:
可能您的服务器发送一些空白(不可打印,空,输入)章程.而你却没有意识到这一点.服务器代码也是错误的.
或者您的服务器在客户端可以阅读之前终止.
还有一件有趣的事情,试着去理解:
当您
write()在服务器上呼叫N时,不需要read()在另一侧进行N 呼叫.
|   归档时间:  |  
           
  |  
        
|   查看次数:  |  
           32203 次  |  
        
|   最近记录:  |