2011-03-08 58 views
1

我有一個小型的客戶機 - 服務器程序,並且我想在超過10秒的最大超時後關閉與客戶機的連接。我有一個報警和關閉連接,報警處理程序看起來像這樣的功能:在C客戶機服務器程序中處理超時

void closeClient() { 
    int nr = close(conn); 
    if (nr == 0) 
     printf("Client connection closed.\n"); 
    else { 
     printf("Error while closing client connection. Error code: %d\n",errno); 
     exit(1); 
    } 
    exit(0); // Process ends after serving the client 
} 

void time_out(int signal) { 
    printf("Time out.\n"); 

    char* msg = "Time out.Connection to server is closed\n\0"; 
    send(conn, msg, strlen(msg),0); 
    closeClient(conn); 
    exit(1); 
} 

的問題是,在客戶端打印消息(「時間out.Connection到服務器關閉」)僅當它會嘗試將某些內容發送給服務器(連接已關閉後)。我無法弄清楚爲什麼。一些建議?

+0

你永遠不會顯示調用time_out函數的代碼。 – YeenFei

+0

就像這樣:'code' signal(SIGALRM,time_out); 報警(10); cod = recv(conn,&buf,sizeof(buf),0); boolean isNumber = validateNumber(buf); printf(「收到的字符串:%s \ n」,buf); 報警(0); //停止計時器 if(!isNumber){//服務器沒有收到有效整數 errorMsg =「請輸入一個有效的整數!\ n \ 0」; 012fprintf(「正在發送錯誤消息.. \ n」); (conn,errorMsg,strlen(errorMsg)+1,0); } else ..'code' – joanna

回答

0

也許你可以使用select()並在最後一個參數中給它一個超時值?

沿東西:

fd_set readset; 
struct timeval timeout = {10, 0}; // 10 sec. timeout 
FD_ZERO(&readset) 
FD_SET(conn, &readset); 
int status = select(conn+1, &readset, NULL, NULL, &timeout); 
if(status == 0) // timeout reached 
{ 
    // close conn 
} 
else if(status == -1) 
{ 
    // handle error 
} 
else 
{ 
    // data ready to be received 
    status = read(conn, ....); 
} 

確保每次檢查返回值。

+0

我很喜歡我處理time_out的方式,它工作正常,或者對我來說似乎是如此。意味着服務器等待10秒鐘才能收到一個字符串;如果它收到該字符串,它會重置警報。信號處理程序(time_out()函數)在我將消息發送到客戶端時的問題是。只有在客戶端嘗試將smth發送到服務器後,纔會顯示此消息,該連接已關閉。我很久沒有在C工作了,很抱歉,如果我沒有很清楚地解釋我自己。 – joanna

+0

我的不好,我沒有回答這個問題的核心。對此,我(我們?)可能需要在客戶端查看代碼。也許你不沖洗打印緩衝區?嘗試在客戶端的init中添加'setbuf(stdout,NULL);'? – Gui13

+0

這有點總和了:'code' printf(「輸入你想要的數字:\ n」); fgets(input,sizeof(input),stdin); (input [strlen(input)-1] =='\ n')input [strlen(input)-1] ='\ 0'; //用於全行讀取 cod = send(conn,input,strlen(input),0); if(cod!= strlen(input)){fderf(stderr,「將數據發送到服務器時出錯。\ n」); return 1; } //服務器響應: cod = recv(conn,buf,sizeof(buf),0); (「服務器的迴應是:\ n \ t%s \ n」,buf); 'code'我試過setbuf(stdout,NULL),就在recv之前,但仍然沒有結果。 – joanna