简体   繁体   English

C中的HTTP代理,recv()不会阻塞?

[英]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. 问题是循环不会在recv暂停,而是继续进行下去,最终程序停止。 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? 如果是这种情况, recv()是否应该给我一个错误? Why does it give back 0 if I want it to block if there is zero data in the socket? 如果套接字中的数据为零,为什么要阻止它,为什么它会返回0?

recv() returns a value which you are completely ignoring: recv()返回一个您完全忽略的值:

  • 0, end of stream: close the socket and exit the read loop. 0,流结束:关闭套接字并退出读取循环。
  • -1: error: unless errno is EAGAIN/EWOULDBLOCK the connection is hosed: close the socket and exit the read loop. -1:错误:除非errnoEAGAIN/EWOULDBLOCK ,否则连接已完成:关闭套接字并退出读取循环。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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