问题描述
尝试在全局线程池的新线程中处理连接的客户端套接字:
Trying to handle a connected client socket in a new thread from global thread pool:
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的回答)。
I have been getting endless errors with these. It seems cross-thread QTcpSocket
handling is not feasible(See Michael's answer).
一些错误:
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
/ p>
Should I handle QTcpSocket
in a different thread ?
What should I do if I want to handle QTcpSocket
in a different thread ?
Or is there way to create a QTcpSocket
from a file descriptor ?
推荐答案
我认为保留您的答案:
为此,您必须继承 QTcpServer
并覆盖虚拟方法。
To do this, you'll have to inherit from QTcpServer
and override the virtual method incomingConnection
.
在该方法中,创建子线程,为子套接字创建一个新的 QTcpSocket
。
Within that method, create the child thread which will create a new QTcpSocket
for the child socket.
例如:
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()
套接字。
这篇关于Qt - 在一个新的线程中处理QTcpSocket的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!