2017-06-21 155 views
0

我需要实现以300 Hz(每秒300个采样)读取数据的客户端。当使用C套接字时,一切都可以接受,因为我需要运行一个连续的while循环来从服务器获取数据(阻止客户端处理其他任何事情)。 所以,我决定尝试移动到QTcpsocket,以处理来自其他对象到客户端对象的信号。但是,当我连接与QTcpSocket,并连接信号读取使用QTcpSocket持续快速使用

connect(socket,&QTcpSocket::readyRead, this, &client::handleReadyRead, Qt::ConnectionType::QueuedConnection); 

这是我的处理程序 -

QByteArray b = socket->read(12); 
int packetLength = (unsigned char)b[6] << CHAR_BIT; 
packetLength |= (unsigned char)b[7]; 
b = socket->read(packetLength); 

(我得到每包12字节长头) 现在我得到一个非常慢速客户端 - 它每秒处理大概3个样本......我检查了看有多少bytesavailable()返回,并且它看起来像数据堆积在套接字缓冲区中。 我在做什么错?我必须得到一个非常快速的客户,但我不确定我阅读的方式是最佳的。 有没有更有效的方法来做到这一点?

谢谢

+2

配置您的应用程序,看看瓶颈在哪里。 –

+0

我实际上使用一个小型项目来测试它,所以它几乎只是客户端运行。分析表明,事件循环需要很长时间,但可以避免吗? – JLev

+0

您正在调用'socket-> read(packetLength)'而不知道'packetLength'字节是否可用。如果它们不是,则下一次读取将与数据流不同步。 –

回答

1

您当前handleReadyRead假设一个完整的数据包可用于读取和数据包边界已被保留。 TCP不能这样工作 - 它只是一个字节流。

更好的方法可能是将数据累加到QByteArray中,并在数据包可用时从该QByteArray中读取数据包。

因此,假设您的client类有一个数据成员...

QByteArray m_data; 

我期望的逻辑是这样的......

void handleReadyRead() 
{ 

    /* 
    * Append all available data to m_data. 
    */ 
    m_data.append(socket->readAll()); 

    /* 
    * Now work our way through m_data processing complete 
    * packets as we find them. At any given point offset 
    * is the total size of all complete packets (including 
    * headers) processed thus far. 
    */ 
    int offset = 0; 
    while (m_data.length() >= offset + 12) { 

    /* 
    * We have enough data for a header so read the packet length. 
    */ 
    int packetLength = (unsigned char)m_data[offset + 6] << CHAR_BIT; 
    packetLength  |= (unsigned char)m_data[offset + 7]; 

    /* 
    * Check to see if we have sufficient data for the packet 
    * body. If not then we're done for the time being. 
    */ 
    if (m_data.length() < offset + 12 + packetLength) 
     break; 

    /* 
    * There is enough data for the complete packet so read it. 
    * Note that the following will include the header data in the 
    * packet variable. If that's not desired then change it to... 
    * 
    * auto packet = m_data.mid(offset + 12, packetLength); 
    */ 
    auto packet = m_data.mid(offset, 12 + packetLength); 

    /* 
    * Do whatever you want with the packet. 
    */ 
    do_something_with_the_packet(packet); 

    /* 
    * Update the offset according to the amount of data read. 
    */ 
    offset += 12 + packetLength; 
    } 

    /* 
    * Finally, remove the data processed from the beginning of 
    * the QByteArray. 
    */ 
    if (offset) 
    m_data = m_data.right(data.size() - offset); 
} 

以上是未经检验的,但肯定是沿着我过去使用的代码行。

+0

这真的很有用,谢谢。现在我只是想知道为什么我要以错误的顺序获取数据包.... – JLev