2016-05-28 4 views
0

クライアントからの応答を待つことに小さな問題があります。コードは次のようになります。Cソケットレスポンスがない場合はクローズ接続

num_bytes_received = recv(recvFD, line, MAX_LINE_SIZE-1, 0); 

    if(line[0] == 'R') 
    { 
     do_something(); 
    } 

    if(line[0] == 'P') 
    { 
     do_another_thing(); 
    } 

は、メッセージのは、30秒を言わせて、何のメッセージ実行do_another_thingは()がない場合を待つ任意の簡単な方法があります。関数?接続の問題の状況(クライアントの切断など)ではありません。それは私が作りたいと思う自分の限界です。

+2

タイムアウトとともに 'select'を使用すると、ソケットの動作を待つことができます。 'SO_RCVTIMEO'を使って' setsockopt'を実行してください。 – user3386109

+0

ありがとう! :) – kotecek

答えて

2

select()をタイムアウトとともに使用できます。

int ret; 
fd_set set; 
struct timeval timeout; 
/* Initialize the file descriptor set. */ 
FD_ZERO(&set); 
FD_SET(recvFD, &set); 

/* Initialize the timeout data structure. */ 
timeout.tv_sec = 30; 
timeout.tv_usec = 0; 

/* select returns 0 if timeout, 1 if input available, -1 if error. */ 
ret = select(recvFD+1, &set, NULL, NULL, &timeout)); 
if (ret == 1) { 
    num_bytes_received = recv(recvFD, line, MAX_LINE_SIZE-1, 0); 
    if(line[0] == 'R') 
    { 
     do_something(); 
    } 

    if(line[0] == 'P') 
    { 
     do_another_thing(); 
    } 
} 
else if (ret == 0) { 
    /* timeout */ 
    do_another_thing(); 
} 
else { 
    /* error handling */ 
} 
+0

魅力的な作品!ありがとうございました! – kotecek

関連する問題