I built a server in Qt
that takes every client that connects to it and sends the connection away to worker thread (I implement this with QRunnable
and I connect the thread to QThreadPool
).
In my thread I read without a problem from the socket (QTcpSocket socket
) but when I try to write to it I get the following error:
QObject: Can not create children for a parent that is in a different thread. The parent thread is QThread (0x28602f90860)
I tried to fix this by adding the code line:
socket->setParent(this);
In the constructor of my thread - but it did not help, I got the following error:
QObject: Cannot create children for a parent that is in a different thread.
(Parent is QNativeSocketEngine(0x1dab6331c60), parent's thread is QThread(0x1dab62eacf0), current thread is QThread(0x1dab632b140)
QSocketNotifier: Socket notifiers cannot be enabled or disabled from another thread
Does anyone know what this problem is or how to solve it?
A sparse example of the relevant code snippets:
class myTask : public QObject , public QRunnable, public parser
{
Q_OBJECT
public:
myTask(QTcpSocket *s)
{
socket = s;
socket->setParent(this);
// if i do here socket->write("hello world"); it's work , but not in run()
}
signals:
void Result(int num);
protected:
void run()
{
socket->write("hello world"); // i get here the error
}
private:
QTcpSocket *socket;
};
/* the creation of the worknig thread and the tcp client creation */
void MyClient::readyRead()
{
myTask * mtask = new myTask(socket);
mtask->setAutoDelete(true);
// connect result to our loacal result function
connect(mtask, SIGNAL(Result(int)), this, SLOT(taskResults(int)), Qt::QueuedConnection);
//start havy job
QThreadPool::globalInstance()->start(mtask);
}
void MyClient::SetSocket(int descriptor)
{
socket = new QTcpSocket(this);
connect(socket, SIGNAL(connected()), this, SLOT(connected()));
connect(socket, SIGNAL(disconnected()), this, SLOT(disconnected()));
connect(socket, SIGNAL(readyRead()), this, SLOT(readyRead()));
socket->setSocketDescriptor(descriptor);
qDebug() <<"[*] client connected";
}
class MyClient : public QObject
{
Q_OBJECT
public:
explicit MyClient(QObject *parent = nullptr);
void SetSocket(int descriptor);
signals:
public slots:
void connected();
void disconnected();
void readyRead();
void taskResults(int num);
private:
QTcpSocket *socket;
};