【问题标题】:Port setsockopt() with RCVTIMEO for Windows CE用于 Windows CE 的带有 RCVTIMEO 的端口 setsockopt()
【发布时间】:2015-10-12 12:45:26
【问题描述】:

我正在将基于套接字的应用程序从 Linux 移植到 Windows CE 6.0。我遇到了一行代码,它设置了接收超时的套接字选项。

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

将接收超时设置为200ms后,调用recv()从远程IP(发送方)接收数据。 第一个链接清楚地解释了生成一个线程并等待它,但是对于我的情况来说,200 毫秒看起来太少了,因为发送者发送了大约 10 秒。 第二个链接的 select() 建议是我添加到代码中的,但行为非常不一致。有时它没有收到任何数据包,有时是 1 个或更多。但是现有的实现在 Linux 上运行良好。

我是否以正确的方式进行移植?谁能指出一个可能的错误或提出建议?

谢谢!

【问题讨论】:

  • 您是否考虑过添加一些错误检查?例如到setsockopt() 通话?

标签: c sockets windows-ce winsock2


【解决方案1】:

我认为移植您的 linux 代码的“select()”建议是正确的。

我会使用以下代码:

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。

希望对你有帮助

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-03-11
    • 2011-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多