简体   繁体   中英

Read from socket freeze

I have problem while reading data from client on server. The read() function will always freeze (block) after all data are readed and waiting for more data what is undesirable for me.

Server program:

   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
   }

Client program:

   ...
   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.

You will need to make your socket non-blocking. The read will immediately exit in that case if there is nothing to be read with a specific error.

Look at C- Unix Sockets - Non-blocking read

As stated earlier use non blocking or add RCV_TIMEOUT to socket.

struct timeval tv;

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

setsockopt(sockid, SOL_SOCKET, SO_RCVTIMEO,(struct timeval *)&tv,sizeof(struct timeval));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM