2015-12-02 129 views
0

我正在使用UDP服務器和客戶端,並且我正在將數據從客戶端發送到服務器,反之亦然。但正如你們知道UDP的「發送和祈禱」,並希望它到達。從for循環超時

我想要一個for循環,如果時間超過'X'秒即使尚未完成也會退出。因爲你不能保證一切都會到來。

有沒有簡單的方法做到這一點,而不會增加我的for循環?

for (int i = 0; i < split ; i++){ 
    iResult = recvfrom(RecvSocket, RecvBuf, BufLen, 0, (SOCKADDR *)& SenderAddr, &SenderAddrSize); 

    cout << "Receiving " << BufLen << endl; 
    sum += BufLen; 

    //IF X seconds goes cancel loop with 
    //timeout something something 
} 
+0

獲取時間,檢查時間差,從循環中斷 –

+3

'select/poll' ..? –

+0

它是操作系統特定的。標準C++ 11不知道套接字。因此,如果編碼爲Linux,請閱讀[高級Linux編程](http://www.makelinux.net/alp/)。參見[poll(2)](http://man7.org/linux/man-pages/man2/poll.2.html),[syscalls(2)](http://man7.org/linux/man- pages/man2/syscalls.2.html),[time(7)](http://man7.org/linux/man-pages/man7/time.7.html),[socket(7)](http: //man7.org/linux/man-pages/man7/socket.7.html),[udp(7)](http://man7.org/linux/man-pages/man7/udp.7.html) ,等... –

回答

0

在循環開始之前設置鬧鐘/定時器。

0

如果你不關心確切的超時,這可能是一個非常簡單的方法:

const int max = 100; 
int count = 0; 

for (int i = 0; i < split; i++){ 
    iResult = recvfrom(RecvSocket, RecvBuf, BufLen, 0, (SOCKADDR *)& SenderAddr, &SenderAddrSize); 

    cout << "Receiving " << BufLen << endl; 
    sum += BufLen; 

    count++; 
    if (count == max) 
    { 
     //something something 
     break; 
    } 
    Sleep(10); 
} 
0
const double MAX_SECONDS = 30; 
double start = omp_get_wtime(); 

for (int i = 0; i < split ; i++) 
{ 
iResult = recvfrom(RecvSocket, RecvBuf, BufLen, 0, (SOCKADDR *)& SenderAddr, &SenderAddrSize); 

cout << "Receiving " << BufLen << endl; 
sum += BufLen; 

double end = omp_get_wtime(); 

//IF X seconds goes cancel loop with 
//timeout something something 
if((end - start) > MAX_SECONDS) 
    break; 
} 

這將在30秒後破環。 更多的信息: https://msdn.microsoft.com/en-us/library/t3282fe5.aspx

+0

我累了,我馬上得到Timeout,我設置了MAX_SECONDS TO 30000 dosnt問題:/ –

+0

您是否包含#include ?結束開始的輸出是什麼? – EylM

1

你可以做的時間可移植使用C + + 11時間功能,例如, std :: chrono等。如果你想從阻塞閱讀中醒來,你需要選擇或輪詢或親戚(epoll/pselect)。