UDP与另一个软件错误

时间:2013-05-31 11:27:35

标签: c visual-studio-2010 udp

我正在使用IPG CarMaker并尝试使用UDP实时将数据导出到另一台机器。 我指的是http://www.codeproject.com/Articles/11740/A-simple-UDP-time-server-and-client-for-beginners。 我想在客户要求时发送汽车的位置。现在我将上面的代码包含在CarMakers主循环中,其时间步长为1 ms。构建程序时(使用Visual Studio 2010)没有问题。但是当我尝试在CarMaker中运行模拟时,以下行会导致模拟超时:

bytes_received = recvfrom(sd,buffer,BUFFER_SIZE,0,(struct sockaddr *)& client,& client_length);

结果我的模拟根本没有开始! 是因为我没有同时在一起运行的客户端吗?请帮忙!主循环中的代码如下:

User_DrivMan_Calc(double dt) {     client_length =(int)sizeof(struct sockaddr_in);

bytes_received = recvfrom(sd, buffer, BUFFER_SIZE, 0, (struct sockaddr *)&client, &client_length);

if (bytes_received < 0)
{
    fprintf(f, "Could not receive datagram.\n");
    closesocket(sd);
    WSACleanup();
    exit(0);
}

/* Check for time request */

if (strcmp(buffer, "GET DISTANCE\r\n") == 0)
{
    /* Get current time */
    current_time = time(NULL);
    d = Car.Distance;       
    /* Send data back */
    if (sendto(sd, (char *)&d, (int)sizeof(d), 0, (struct sockaddr *)&client, client_length) != (int)sizeof(d))
    {
        fprintf(f, "Error sending datagram.\n");
        closesocket(sd);
        WSACleanup();
        exit(0);
    }
}

return 0;

}

1 个答案:

答案 0 :(得分:0)

这是一个阻塞读取,即在读取成功之前它不会从函数返回。

如果没有数据等待,它将会阻塞很长时间。

您需要使用例如select()检测数据何时可用,或make the socket non-blocking

此外,如果您的数据包速率为1,000 Hz,那么对于这种应用来说,这种方式通常会太快。