Qt-在新螺纹中处理QTcpSocket
Qt - Handle QTcpSocket in a new thread
尝试在全局线程池的新线程中处理连接的客户端套接字:
m_threadPool = QThreadPool::globalInstance();
void TCPListenerThread::onNewConnection()
{
QTcpSocket *clientSocket = m_tcpServer->nextPendingConnection();
clientSocket->localPort();
m_connectThread = new TCPConnectThread(clientSocket);
m_threadPool->start(m_connectThread);
}
这是TCPConnectThread
:
class TCPConnectThread : public QRunnable {
TCPConnectThread::TCPConnectThread(QTcpSocket *_socket)
{
m_socket = _socket;
this->setAutoDelete(false);
}
void TCPConnectThread::run()
{
if (! m_socket->waitForConnected(-1) )
qDebug("Failed to connect to client");
else
qDebug("Connected to %s:%d %s:%d", m_socket->localAddress(), m_socket->localPort(), m_socket->peerAddress(), m_socket->peerPort());
if (! m_socket->waitForReadyRead(-1))
qDebug("Failed to receive message from client") ;
else
qDebug("Read from client: %s", QString(m_socket->readAll()).toStdString().c_str());
if (! m_socket->waitForDisconnected(-1))
qDebug("Failed to receive disconnect message from client");
else
qDebug("Disconnected from client");
}
}
我一直在犯这些错误。跨线程QTcpSocket
处理似乎不可行(参见Michael的回答(。
一些错误:
QSocketNotifier: socket notifiers cannot be disabled from another thread
ASSERT failure in QCoreApplication::sendEvent: "Cannot send events t objects owned by a different thread.
我应该在另一个线程中处理QTcpSocket
吗
如果我想在不同的线程中处理QTcpSocket
,该怎么办
或者有没有办法从文件描述符创建QTcpSocket
?
我想这个页面包含了你的答案:
如果要将传入连接处理为新的QTcpSocket对象,则必须将socketDescriptor传递给其他线程,并在那里创建QTcpSocket对象,并使用其setSocketDescriptor((方法。
要做到这一点,您必须从QTcpServer
继承并覆盖虚拟方法incomingConnection
。
在该方法中,创建将为子套接字创建新QTcpSocket
的子线程。
例如:
class MyTcpServer : public QTcpServer
{
protected:
virtual void incomingConnection(int socketDescriptor)
{
TCPConnectThread* clientThread = new TCPConnectThread(socketDescriptor);
// add some more code to keep track of running clientThread instances...
m_threadPool->start(clientThread);
}
};
class TCPConnectThread : public QRunnable
{
private:
int m_socketDescriptor;
QScopedPointer<QTcpSocket> m_socket;
public:
TCPConnectionThread(int socketDescriptor)
: m_socketDescriptor(socketDescriptor)
{
setAutoDelete(false);
}
protected:
void TCPConnectThread::run()
{
m_socket.reset(new QTcpSocket());
m_socket->setSocketDescriptor(m_socketDescriptor);
// use m_socket
}
};
或者尝试在套接字上使用moveToThread()
。
相关文章:
- 警告处理为错误这里有什么问题
- 在C#中处理C++指针而不使用unsafe的最佳方法
- 处理多个异常集合的C++方法
- 找不到成员对象:没有名为get_event()的成员,也处理多态性和向量
- 使用流处理接收到的数据
- 获取日期异步信号安全吗?如果在信号处理程序中使用,它会导致死锁吗
- 处理小于cpu数据总线的数据类型.(c++转换为机器代码)
- 基于多个条件处理地图中的所有元素
- 如何用数字处理log(0)
- SSL上的`curl_easy_send`和`curl_asy_recv`:如何处理`CURLE_AGAIN`
- 错误处理.将系统错误代码映射到泛型
- 从文本文件中读取时钟时间和事件时间并进行处理
- 在运行时处理类型擦除的数据-如何不重新发明轮子
- 在for循环中使用auto vs decltype(vec.size())来处理字符串的向量
- 用于矢量处理的多个线程
- 对字符串进行排序时,在c++中处理sort()
- 如何处理linux终端中带有负号(-)的C++中的命令行参数
- 处理除以零会导致<csignal>意外行为
- 是否可以在c++中处理字符串流中的各个元素
- Qt-在新螺纹中处理QTcpSocket