Theodore Tang
Theodore Tang

Reputation: 1021

Multi thread server can not read messages from clients in Qt

Trying to implement a multi thread server in Qt, just consider this:

in SocketThread class:

SocketThread::SocketThread(qintptr descriptor, QObject *parent)
    : QThread(parent), socketDescriptor(descriptor)
{
    socket = new QTcpSocket();
    socket->setSocketDescriptor(socketDescriptor);

    socket->moveToThread(this);

    connect(socket, &QTcpSocket::readyRead, [this]() { qDebug() << socket->readAll(); }); //trying to read messages from clients
} 

in Connection class: creating thread in incomingConnection()

void Connection::incomingConnection(qintptr socketDescriptor)
{
    SocketThread *socketThread = new SocketThread(socketDescriptor);
    socketThread->start();

    connect(socketThread, &SocketThread::started, [&]() { socketThread->socket->write("Hello!"); });  //write a message to client when thread is created
}

Strange thing is, if I add this line:

connect(socketThread, &SocketThread::started, & { socketThread->socket->write("Hello!"); }); //write a message to client when thread is created

Then the socket will not read message from client. If I remove that line, the socket will read message from client.

I want the server to send message to client when a thread is created and to read message from client as well. How can do solve the problem?

Edit:

SocketThread header file:

class SocketThread : public QThread
{
    Q_OBJECT
public:
    SocketThread(qintptr descriptor, QObject *parent = 0);
    ~SocketThread();
    QTcpSocket *socket;
    qintptr socketDescriptor;
};

in the Connection constructor:

Connection::Connection(QObject *parent) : QTcpServer(parent)
{
    this->listen(QHostAddress::Any, 6666);
}

And creating a connection object in the main.cpp file. That's really like all the code.

Upvotes: 0

Views: 88

Answers (0)

Related Questions