【问题标题】:Porting socket interface from Qt to STD library将套接字接口从 Qt 移植到 STD 库
【发布时间】:2021-05-17 05:09:00
【问题描述】:

我正在尝试将 Qt 套接字接口移植到 STD 库套接字接口。我正在构建一个类似于我在 STD 中的 Qt 包装器的包装器。

QTcpSocket 接口非常方便,因为它提供了如下信号:

connect(m_pSocket, SIGNAL(connected()),    this, SLOT(onConnected()));
connect(m_pSocket, SIGNAL(disconnected()), this, SLOT(onDisconnected()));
connect(m_pSocket, SIGNAL(readyRead()),    this, SLOT(onReadyRead()));

不幸的是,STD 不提供这些,所以我的主要问题是关于读取数据。我在 Qt 中的做法是将 QTcpSocket readyRead 信号连接到我在包装器中编写的函数:

void MyClass::onReadyRead()
{
    // Input buffer is empty so new message
    bool isNewMsg = m_inBuffer.isEmpty();

    // Read available data in socket into input buffer
    m_mutex.lock();
    while (m_pSocket->bytesAvailable() > 0)
    {
        m_inBuffer.append(m_pSocket->readAll());
    }
    m_mutex.unlock();

    // If new message extract full receive length
    if (isNewMsg)
    {
        const char* inBuf = (const char *) m_inBuffer.data();

        m_expRcvLen = atoi((char *)inBuf) + SOCKET_HEADER_LENGTH;
    }

    int currRcvLen = m_inBuffer.size();
    if (currRcvLen < m_expRcvLen)
    {
        // Expecting more packets
        return;
    }

    // Reset for next message
    m_expRcvLen = 0;

    // Emit signal data read form socket
    emit dataReceived(m_inBuffer);
}

我想我的问题是如何在 STD 库和可能的 libsigc++ 中实现相同的行为:

  • 非阻塞套接字
  • 数据可用时的通知

【问题讨论】:

    标签: c++ qt sockets std nonblocking


    【解决方案1】:

    您正在寻找的行为将要求您使用 unix 上的 poll 或 windows 上的 IoCompletion 端口编写自己的执行程序。不是一个简单的练习。

    作为 boost 一部分的 asio 库有自己的执行器。它还提供了async_connectasync_read 这两个回调,它们可以使用与您提供的Qt 插槽类似的功能。

    【讨论】:

      猜你喜欢
      • 2011-06-04
      • 2011-05-13
      • 1970-01-01
      • 1970-01-01
      • 2021-05-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多