我正在使用IPG汽车制造商,并试图使用UDP实时将数据导出到另一台机器。我指的是http://www.codeproject.com/Articles/11740/A-simple-UDP-time-server-and-client-for-beginners。我想在客户端请求时发送汽车的位置。现在我已经将上面的代码包含到汽车制造商的主循环中,它的时间步长为1毫秒。在我构建程序(使用Visual Studio 2010)时没有问题。但是,当我尝试在汽车制造商中运行模拟时,以下行会导致模拟超时:
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 DISTANCErn") == 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;
}
这是一个阻塞式读取,即在读取成功之前它不会从函数返回。
如果没有数据正在等待,它将阻塞很长时间。
您需要使用例如select()
来检测何时有数据可用,或者使套接字非阻塞。
另外,如果你的数据包速率是1000hz,那么对于这种应用程序来说,这通常太快了。