Writing data to TcpSocket in its own stream

I am having a problem with my streaming TCP server.
I can open my Server, a new Socket is created, I can receive data on the socket (I used the readyRead () signal and then used readLine () to read, which works fine. Now I want to write data to this Socket from another stream, so I created a public writeData () slot that should take care of this.I connected the writeData () slot with QueuedConnection (also tried AutoConnection), but all I get when I call m_socket-> write () is a message error:

QObject: Unable to create children for a parent that is in another thread. (Parent of QNativeSocketEngine (0x12f0f70), the parent thread is ServerThread (0xfbbae8), the current thread is QThread (0xfa7c48)

Just a minimal example:
I missed a connection from my other stream into the writeData () slot, because I think everyone can imagine it;)

class Server : public QTcpServer {
  Server();
protected:
  void incomingConnection(int socketDesc);
}

Server::Server() : QTcpServer() {
  this->listen(QHostAddress::Any, PORT);
}

void Server::incomingConnection(int socketDescriptor) {
  ServerThread *t = new ServerThread(socketDescriptor);
  t->start();
}

class ServerThread : public QThread {
  ServerThread(int socketDescriptor);
protected:
  void run();
public slots:
  void writeData(QString data);
private:
  int m_socketDescriptor;
  QTcpSocket *m_socket;
}

ServerThread::ServerThread(int socketDescriptor) : QThread(), m_socketDescriptor(socketDescriptor) {}

void ServerThread::run() {
  m_socket = new QTcpSocket();
  m_socket->setSocketDescriptor(m_socketDescriptor);
  exec();
}

void ServerThread::writeData(QString data) {
  m_socket->write(data.toAscii());
}

Thanks in advance.

+3
source share
1 answer

Your error message means:

Your signal slot communicates with the ServerThread instance that was created and belongs to the main thread. However, an instance of the ServerThread m_socket was created and belongs to a different thread.

QThread .

void Server::incomingConnection(int socketDescriptor) {
  QThread *t = new QThread();
  ClientConnection *client = new ClientConnection(socketDescriptor);
  client->moveToThread(t);

  // go
  t->start();
}

class ClientConnection : public QObject {
Q_OBJECT
public:
  ClientConnection(int socketDescriptor, QObject *parent = 0);
public slots:
  void writeData(QString data);
private:
  int m_socketDescriptor;
  QTcpSocket *m_socket;
}
+5

Source: https://habr.com/ru/post/1789495/


All Articles