0

从服务器上的客户端读取数据时出现问题。在读取所有数据并等待更多数据后,read() 函数将始终冻结(阻塞),这对我来说是不受欢迎的。

服务器程序:

   soc = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); 
   struct sockaddr_in sin;  
   sin.sin_family = AF_INET;  
   sin.sin_port = htons(port);   
   sin.sin_addr.s_addr = INADDR_ANY; 
   bind(soc, (struct sockaddr*) &sin, sizeof(sin));

   if (listen(soc, MAX))
      return;

   int socc;               // socket for clinet     
   while (1) {
      if ((socc = accept(soc, (struct sockaddr *) &sin, sinlen)) < 0)
         break;
      while ((result = read(socc, pointer, SIZE)) > 0) {
         // after the data are readed, read function will block
      }
      // do some stuff and write reply to client => will never done
   }

客户端程序:

   ...
   soc = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)  
   struct sockaddr_in socketAddr;
   socketAddr.sin_family = AF_INET;
   socketAddr.sin_port = htons(port);
   memcpy(&(socketAddr.sin_addr), host->h_addr, host->h_length);
   if (connect(soc, (sockaddr *)&socketAddr, sizeof(socketAddr)) == -1)  
      return;
   if (write(soc, req.c_str(), strlen(req.c_str())) < 0)
      return;

The main problem is that I don't know how much data will be client sending to server, so the server should read all data from socket and after nothing is coming, leave the reading cycle. But the server read whole message for example (30 bytes) and waiting for more (but no more is coming). The sockets are still opened because the client is waiting for reply from server.

4

2 回答 2

2

如前所述,使用非阻塞或将 RCV_TIMEOUT 添加到套接字。

struct timeval tv;

tv.tv_sec = 30;  /* 30 Secs Timeout */

setsockopt(sockid, SOL_SOCKET, SO_RCVTIMEO,(struct timeval *)&tv,sizeof(struct timeval));
于 2013-03-10T05:47:55.227 回答
2

您将需要使您的套接字非阻塞。在这种情况下,如果没有要读取的内容出现特定错误,读取将立即退出。

看看C- Unix Sockets - 非阻塞读取

于 2013-03-10T05:40:31.317 回答