我正在尝试将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++中获得相同的行为来实现:
数据可用时的非阻塞Socket
发布于 2021-02-13 20:53:50
您正在寻找的行为将要求您使用unix上的轮询或windows上的IoCompletion端口来编写您自己的执行器。不是一个琐碎的练习。
asio库是boost的一部分,它有自己的执行器。它还提供了async_connect和async_read,这两种回调都可以使用类似于您提供的Qt插槽的函数。
https://stackoverflow.com/questions/66188967
复制相似问题