我是一个初学者在c + +套接字编程,我有一个问题,我试图处理一段时间。C++多UDP套接字数据处理
我的任务是处理来自两个不同传感器的数据。我通过UDP套接字接收数据,然后处理数据包(显然,所有这些都发生在一个while循环中)。我将数据用于实时可视化,因此我需要整个过程快速。
只要我尝试从一个传感器接收数据,一切都可以。当我想用两个传感器来完成它(因此在一个循环中有两个recvfrom()函数),这就是我的问题何时开始。处理过程非常缓慢,因此我错过了一些数据包。我意识到recvfrom()函数是一个阻塞调用,我用select()函数处理它,因此我知道它不是问题的根源。
这里是一个似乎是负责做文章部分代码:
while (1)
{
SingleSocketReceiver(&socket_1, port_1, scene_1, ptrScene_1, model);
SingleSocketReceiver(&socket_2, port_2, scene_2, ptrScene_2, model);
}
当我发表意见的第二SingleSocketReceiver()函数,一切工作正常。
这里是什么SingleSocketReceiver()函数包括:
int SingleSocketReceiver(UDPsocket* socket, uint16_t port,pcl::PointCloud<pcl::PointXYZ> scene, pcl::PointCloud<pcl::PointXYZ>::Ptr ptrScene, pcl::PointCloud<pcl::PointXYZ>::Ptr model)
{
struct timeval tv;
fd_set rfds;
FD_ZERO(&rfds);
FD_SET(socket->pSocket,&rfds);
tv.tv_sec = 1;
tv.tv_usec = 0;
if ((socket->rc = select(FD_SETSIZE,&rfds,NULL,NULL,&tv)) < 0)
{
printf("Port No. %d: ERROR! - no data received!\n", port);
return RESULT_ERROR;
}
else if (socket->rc == 0)
{
printf("Port No. %d: Timeout - no data received!\n", port);
return RESULT_ERROR;
}
socket->rc=recvfrom(socket->pSocket,(char*)socket->udpPacketBuf,UDP_PACKET_BUF_LEN,0,&socket->remoteAddr,&socket->remoteAddrLen);
if(socket->rc==SOCKET_ERROR)
{
printf("Socket for port No.%d: Error in recvfrom\n", port);
return RESULT_ERROR;
}
else
{
// Check the packet counter for missing packets
if (socket->previous_packet_counter_valid)
{
if ((socket->ph->PacketCounter - socket->previous_packet_counter) != 1)
{
printf("Port No.%d: Packet Counter jumped from %u to %u (missing packets; try to redirect output)\n", port, socket->previous_packet_counter, socket->ph->PacketCounter);
socket->startOfChannelFound = 0;
}
}
socket->previous_packet_counter = socket->ph->PacketCounter;
socket->previous_packet_counter_valid = 1;
// is this the channel with our data?
if (socket->ph->ChannelID == socket->customerDataChannel)
{
if (socket->ph->IndexOfPacketInChannel == 0)
{
socket->startOfChannelFound = 1;
if (socket->channel_buf_size == 0)
{
socket->channel_buf_size = socket->ph->TotalLengthOfChannel;
socket->channelBuf = (int8_t*) malloc(socket->channel_buf_size);
}
// as we reuse the buffer we clear it at the beginning of a transmission
memset(socket->channelBuf, 0, socket->channel_buf_size);
socket->pos_in_channel = 0;
}
if (socket->startOfChannelFound)
{
processPacket(socket->udpPacketBuf, socket->rc, socket->channelBuf, socket->channel_buf_size, &socket->pos_in_channel);
if (socket->ph->IndexOfPacketInChannel == socket->ph->NumberOfPacketsInChannel -1)
{
processChannel8(socket->channelBuf, socket->pos_in_channel);
displayData();
createPointCloud(scene, ptrScene, model);
}
}
}
}
return RESULT_OK;
}
我会,如果有人认为真正的问题可能是什么非常感激和处理它的可能方式是什么?不幸的是,我无法向您展示我的整个源代码,因为我为我的工作做了这些工作,而且我不允许公开展示它。
请原谅我缺乏这方面的知识。我愿意回答所有其他问题。
非常感谢你!这有助于:) – nanasable