-4

以下c socket编程代码一直在循环,无需等待从文件描述符中获取数据。这是服务器端套接字编程的一部分。它不等待接受来自客户端的请求。请帮忙。

代码:

while(1){  
  bzero(buffer,256);
  read(newsockfd,buffer,256);  
  printf("%s",buffer);  
  if(n<0){
    printf("reading client message failed\n");    
    return 0;
  }  
  printf("success\n");  

}  
4

1 回答 1

1

您没有将返回值分配read()给您的n变量,但您希望n以某种方式知道何时read()失败。修复该分配,然后还修复您的循环逻辑以仅输出实际读取的字节,例如:

while(1){  
  memset(buffer,0,256);
  printf("sssssssss\n");  
  n = read(newsockfd,buffer,256);
  if(n<0){
    // if your sockeet is non-blocking then uncomment this code...
    /*
    if ((errno == EAGAIN) || (errno == EWOULDBLOCK)){
        fd_set rfd;
        FD_ZERO(&rfd);
        FD_SET(newsockfd, &rfd);

        struct timeval timeout;
        timeout.tv_sec = 5;
        timeout.tv_usec = 0;

        if (select(newsockfd+1, &rfd, NULL, NULL, &timeout) > 0){
            continue;
        }
    }
    */
    printf("reading client message failed\n");    
    return 0;
  }  
  if(n==0){
      break;
  }  
  printf("%.*s\n",n,buffer);  
  printf("succcccccccccccccc\n");  
}  
于 2013-01-15T19:10:04.217 回答