【问题标题】:UDP winsock server c++UDP winsock服务器C++
【发布时间】:2016-02-26 00:29:33
【问题描述】:

我正在使用 UDP 连接进行一些套接字编程。我已经编写了我的服务器(它也为 NTP 服务器提供了一个偏移量),但是当我对其进行单元测试时,它在 recvfrom 函数中失败了。我是 Winsock 编程和一般网络编程的新手,所以我不确定从这里去哪里。这是我的代码:

NtpServer::NtpServer(u_short portnum, const std::chrono::nanoseconds desiredOffset) : portnum(0), client_length(0), bytes_received(0), current_time(0), desiredOffset(0)
{
    WORD wVersionRequested;
    wVersionRequested = MAKEWORD(2, 2);
    WSADATA wsaData;

    int iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
    if (WSAStartup(wVersionRequested, &wsaData) != 0)
    {

        std::cerr << "Could not open Windows connection" << std::endl;
        exit(0);
    }

    sd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sd == INVALID_SOCKET)
    {
        std::cerr << "Could not create socket." << std::endl;
        WSACleanup();
        exit(0);
    }

    //blocking enabled
    u_long iMode = 0;

    iResult = ioctlsocket(sd, FIONBIO, &iMode);
    if (iResult != NO_ERROR)
        std::cerr << "ioctlsocket failed with error: " << iResult << std::endl;


    memset((void *)&server, '\0', sizeof(struct sockaddr_in));
    server.sin_family = AF_INET;
    server.sin_addr.s_addr = htonl(INADDR_ANY);
    server.sin_port = htons(portnum);


    if (bind(sd, reinterpret_cast<SOCKADDR *>(&server),
        sizeof(server)) == -1)
    {
        std::cerr << "Could not bind name to socket" << std::endl;
        closesocket(sd);
        WSACleanup();
        exit(0);
    }
    getResult(desiredOffset);
}

和getResult函数:

void NtpServer::getResult(const std::chrono::nanoseconds desiredOffset)
{
    ntp_data ntpData = ntp_data();
    //struct for timeout
    struct timeval tv;
    tv.tv_sec = 10;  // 10 Secs Timeout 
    setsockopt(sd, SOL_SOCKET, SO_RCVTIMEO, (char *)&tv, sizeof(struct timeval));

    while (1)
    {
        client_length = (int)sizeof(struct sockaddr_in);

        /* Receive bytes from client */
        bytes_received = recvfrom(sd, sendBuffer, NTP_PACKET_MAX, 0, (struct sockaddr *)&client, &client_length);
        if (bytes_received < NTP_PACKET_MIN)
        {
            std::cerr << "Could not receive datagram." << std::endl;
            closesocket(sd);
            WSACleanup();
            exit(0);
        }



        /* Check for time request */
        if (strcmp(readBuffer, "GET TIME\r\n") == 0)
        {
            /* Get current time */
            system_clock::time_point now = std::chrono::system_clock::now();
            auto timepointoffset = (now + desiredOffset).time_since_epoch();
            double current_value = std::chrono::duration_cast<std::chrono::duration<double>>(timepointoffset).count();

            unpack_ntp(&ntpData, (unsigned char*)readBuffer, bytes_received);
            make_packet(&ntpData, NTP_CLIENT, current_value);
            pack_ntp((unsigned char *)sendBuffer, NTP_PACKET_MIN, &ntpData);


            /* Send data back */
            if (sendto(sd, sendBuffer,
                (int)sizeof(sendBuffer), 0,
                (struct sockaddr *)&client, client_length) !=
                (int)sizeof(current_time))
            {
                std::cerr << "Error sending datagram." << std::endl;
                closesocket(sd);
                WSACleanup();
                exit(0);
            }
        }
    }
        closesocket(sd);
        WSACleanup();


}

【问题讨论】:

  • 代码太多,实际问题的细节很少。
  • 好吧,如果我尝试运行我的单元测试,它会显示“活动测试运行已中止,因为执行过程意外退出。要进一步调查,请在机器级别或进程 vstest 启用本地故障转储.executionengine.x86.exe。”当我调试时,当它到达 recvfrom 函数时,“bytes_received”小于 NTP_PACKET_MIN。
  • 谢谢我会删除我的评论
  • 接收多少字节?
  • 这是一个.dll,所以我不确定是否有办法直接测试它。我知道,从之前的“if”块中,它得到了 -1,我认为这是一个错误。

标签: c++ sockets network-programming udp winsock


【解决方案1】:

您必须测试来自recvfrom() 的错误——您正在设置 SO_RCVTIMEO,因此您可以预期接收超时。

真的要启用读取超时吗?如果是这样,当你设置 SO_RCVTIMEO 时,设置tv.tv_usec = 0。你让它未初始化。如果 tv_usec 恰好是一个无效值(小于 0 或大于 999,999),那么 setsockopt() 调用应该会失败。

【讨论】:

  • 我的任务要求我使用超时,是的。我想我很困惑你说我要离开 tv.tv_usec 未初始化。我不是设置为 10 吗?
  • 您将 tv.tv_sec(超时的整个第二部分)设置为 10,但还有一个 tv.tv_usec 组件,它以微秒为单位,必须介于 0 和 999,999 之间。例如,如果您希望超时约为 10 秒,请执行 tv.tv_sec = 10; tv.tv_usec = 0;。如果您希望超时大约为 10.5 秒,请执行 tv.tv_sec = 10; tv.tv_usec = 500000;。有关详细信息,请参阅gnu.org/software/libc/manual/html_node/Elapsed-Time.html
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-11-30
  • 1970-01-01
  • 2017-12-24
  • 2018-01-03
  • 1970-01-01
  • 2012-04-18
  • 1970-01-01
相关资源
最近更新 更多