2015-10-12 33 views
-1

我正在將基於套接字的應用程序從Linux移植到Windows CE 6.0。我遇到了一行代碼,它爲接收超時設置了套接字選項。用於Windows CE的端口setsockopt()與RCVTIMEO

struct timeval timeout = 200; timeout.tv_usec = 200000; setsockopt(mySock, SOL_SOCKET, SO_RCVTIMEO, (char *)&timeout, (socklen_t) sizeof(timeout));

我尋找可能的移植實現,並且能找到這兩個線程相關的。 setsockopt() with RCVTIMEO is not working in windows mobile5Set timeout for winsock recvfrom

設定接收超時爲200毫秒之後,存在到的recv()的調用,用於從遠程IP(發送者)接收數據。 清楚地解釋第一個鏈接產生一個線程並等待它,但200ms看起來太少,因爲發件人發送約10秒。 第二個鏈接的select()建議是我添加到我的代碼中的,但行爲非常不一致。有時它不會收到數據包,有時會收到1個,有時甚至更多但現有的實現在Linux上正常工作。

我在做正確的移植嗎?任何人都可以指出可能的錯誤或提出建議嗎?

謝謝!

+0

您是否考慮添加一些錯誤檢查?例如到'setsockopt()'調用? – EJP

回答

0

我認爲「select()」建議移植你的linux代碼是正確的。

我會用下面的代碼:

struct timeval tmout; 

#ifdef LINUX 
//... 
#else 
while (true) 
{ 

      struct fd_set fds; 
      // Set up the file descriptor set. 
      FD_ZERO(&fds) ; 
      FD_SET(mySock, &fds) ; 

      // Set up the struct timeval for the timeout. 
      tmout.tv_sec = 0 ; 
      tmout.tv_usec = 200000 ; 

      // Wait until timeout or data received. 

      n = select (NULL, &fds, NULL, NULL, &tmout) ; 

      if (n == 0) 
      { 
      printf("select() Timeout..\n"); 
      //return 0 ; 
      } 
      else if(n == SOCKET_ERROR) 
      { 
      printf("select() Error!! %d\n", WSAGetLastError()); 
      //return 1; 
      } 
      else 
       printf("select() returns %d\n", n); 
} 
#endif 

我跑在WCE6應用程序相同的代碼,它是對我工作的罰款。 如果您在循環中執行此代碼,並且您的發件人每10秒發送一次,則應每10秒查看一次返回n> 0的選擇。

希望這有幫助

+0

真的嗎? 'struct timeval timeout = 200'對你來說看起來不錯? – EJP

+0

我編輯並澄清了我的答案 – salvolds