简体   繁体   中英

HTTP proxy in C, recv() doesn't block?

I tryied to traceback the behaviour and made up this minimal code to illustrate the problem.

What I try to do is to have a persistent connection with the client( browser ) indefinetely. The idea is that the program waits for the client to request a page and then sends a static page back.

int main(){

   // Set-up proxy and wait for 1 user
   int sock;
   proxy_listen(&sock, DEFAULT_PORT, 1);
   printf("Proxy has started..\n");
   puts("Waiting for user to connect..");
   int sock_user = accept(sock, (struct sockaddr*)NULL, NULL);
   printf("User connected.\n");


   while (1){

      // Receive client's request
      char buff[1000];
      int got = recv(sock_user, buff, sizeof(buff), 0); // IT WON'T BLOCK HERE
      printf("Client sent bytes: %d\n", got);


char *resp="\HTTP/1.1 200 OK\r\n\
Content-Length: 68\r\n\
Connection: close\r\n\r\n\
<!DOCTYPE html><html><head></head><body><p>Got it!</p></body></html>\r\n";


      // Send response
      int sent = send(sock_user, resp, strlen(resp), 0);
      printf("Proxy sent bytes: %d\n", sent);

   }
    return 0;
}

Output:

Proxy has started..
Waiting for user to connect..
User connected.
Client sent bytes: 1000
Proxy sent bytes: 145
Client sent bytes: 416
Proxy sent bytes: 145
Client sent bytes: 0
Proxy sent bytes: 145
Client sent bytes: 0

The problem is that the loop doesn't pause on recv but instead goes on and on and eventually the program stops. Why is that?

Setting close to keep-alive in the response seems to solve this. I assume the server side has closed the connection after the first response. If that is the case, shouldn't recv() give me an error? Why does it give back 0 if I want it to block if there is zero data in the socket?

recv() returns a value which you are completely ignoring:

  • 0, end of stream: close the socket and exit the read loop.
  • -1: error: unless errno is EAGAIN/EWOULDBLOCK the connection is hosed: close the socket and exit the read loop.

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