2013-10-22 80 views
0

我嘗試追溯行爲並編寫了這個最小的代碼來說明問題。C代碼中的HTTP代理,recv()不會阻塞?

我試圖做的是與客戶端(瀏覽器)有一個持久的連接不確定。這個想法是,程序等待客戶端請求一個頁面,然後發回一個靜態頁面。

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; 
} 

輸出:

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 

的問題是,循環不上的recv暫停,而是繼續和,並最終在程序停止。這是爲什麼?

設置接近保活的反應似乎解決這個問題。我假設服務器端在第一個響應後關閉了連接。如果是這樣的話,不應該recv()給我一個錯誤?如果我希望在套接字中存在零數據時阻止它,爲什麼它會返回0?

+0

您應該檢查recv的返回值。 -1意味着發生了錯誤 – Evans

+0

我這樣做。它總是返回0。 – Pithikos

+0

「檢查」並不意味着只是將其打印出來。代碼的行爲不同。你有沒有考慮閱讀文檔? – EJP

回答

1

recv()返回一個值,你完全忽略:

  • 0,流的末尾:關閉套接字,並退出讀取循環。
  • -1:錯誤:除非errnoEAGAIN/EWOULDBLOCK連接被關閉:關閉套接字並退出讀取循環。
+0

但正如我所提到的,我想保持與用戶的持續連接。 – Pithikos

+1

在關閉他的結尾之後,您無法「與用戶保持連接」,這是零的含義。 – EJP