0

I have some trouble with QTcpSockets in combination with Threads.

I guess I have misunderstood the documentation regarding Threads, maybe you can explain where my mistake lies. What part should go into the run() method, and when a signal is emitted and connected to a slot on the threaded class, where is it received? In the "base", not in the run(), right? So how do i notify the "running" part that there is something it has to do? A Shared Object? How?

What I want to archive in the end is the following:

             +-----------------------+
             |      Server           |
             |  keeps some global    |
             |        objects        |
             +--X----------------X---+
                X                X
+---------------X---+         +--X----------------+
|                   |         |                   |
| Thread for Client |         | Thread for Client |
|       B           |         |        A          |
|  keeps local data |         | keeps local data  |
+-----------X-------+         +-----------X-------+
            X                             X
            X                             X
  +---------X----+               +--------X-----+
  |   Socket     |               |   Socket     |
  +-------+---+--+               +----+---+-----+
          ^   |                       |   ^    
          |   |    ----------------   |   |    
          |   |         Network       |   |    
          |   |    ---------------    |   |    
          |   |                       |   |       +----------------+
          |   |                       |   |       |                |
          |   |                       |   +-------+   Client A     |
          |   |                       |           |                |
          |   |                       +---------->+----------------+
          |   |
          |   |                                      +----------------+
          |   +------------------------------------->+                |
          |                                          |   Client B     |
          +------------------------------------------+                |
                                                     +----------------+

Below added code works gives "QSocketNotifier: Socket notifiers cannot be enabled or disabled from another thread". My earlier approach (without code here) gave "QObject: Cannot create children for a parent that is in a different thread.". I also did read the Events-Threads-Objects wiki article (https://wiki.qt.io/Threads_Events_QObjects), but I guess I got something mixed up.

What do I have to change here, that client A can send data to the server, the server changes the data and passes the answer to client A and B (I will set keep-alive option to the socket in the real application, but left it out here for simplification reasons). All "clients" (their threads) have to be able to read and modify objects from the server. What is the best approach for doing this? I guess I should use signal and slots here, and autoconnection should be good enough (I am OK if all threads are notified to send out data at once, i have a reciever id in my protocol, so I can check if the message should be discarded before calling write().

server.pro:

QT += network
QT += core

HEADERS = \
    server.h \
    clientthread.h

SOURCES = \
    main.cpp \
    server.cpp \
    clientthread.cpp

clietthead.h:

#ifndef CTHREAD_H
#define CHREAD_H

#include <QThread>
#include <QTcpSocket>

class ClientThread : public QThread {
    Q_OBJECT

public:
    ClientThread(int socketDescriptor, QObject *parent);

    void run() Q_DECL_OVERRIDE;

     QTcpSocket * tcpSocket;

public slots:
    void slot_msg_answer();
    void slot_request_msg_FromServer();

signals:
    void error(QTcpSocket::SocketError socketError);
    void signal_for_Server_request_msg();

private:
    int socketDescriptor;

};

#endif

server.h

#ifndef SERVER_H
#define SERVER_H    
#include <QTcpServer>

class Server : public QTcpServer {
    Q_OBJECT

signals:
void signalFor_PT_msg_answert(QString);

public:
    Server(QObject *parent = 0);

public slots:
    void slot_request_msg();

protected:
    void incomingConnection(qintptr socketDescriptor) Q_DECL_OVERRIDE;

private:

};
#endif

clientthread.cpp

#include "clientthread.h"
#include <QTcpSocket>
#include <QtNetwork>

ClientThread::ClientThread(int socketDescriptor, QObject *parent)
    : QThread(parent), socketDescriptor(socketDescriptor) {
}

void ClientThread::slot_request_msg_FromServer() {
    emit signal_for_Server_request_msg();
  }

void ClientThread::run() {
    tcpSocket = new QTcpSocket();
    tcpSocket->setSocketOption(QAbstractSocket::KeepAliveOption, true);
    if (!tcpSocket->setSocketDescriptor(socketDescriptor)) {
        emit error(tcpSocket->error());
        return;
    }
    QByteArray ba ( "foo");
    tcpSocket->write(ba);
    tcpSocket->flush();
    exec();
}

void ClientThread::slot_msg_answer() {
    QByteArray ba ("bar");
    tcpSocket->write(ba);
    tcpSocket->flush();
}

main.cpp

#include <QtCore>
#include "server.h"

int main(int argc, char *argv[]) {
    QCoreApplication app(argc, argv);
       Server server_;
 if (!server_.listen(QHostAddress::Any, 1234)) {
        qDebug() << "unable to start the server";
        return -1;
    }
    return app.exec();
}

server.cpp

#include "server.h"
#include "clientthread.h"
#include <QTimer>

Server::Server(QObject *parent) : QTcpServer(parent) {
}

void Server::slot_request_msg() {
    emit signalFor_PT_msg_answert("hello");
}

void Server::incomingConnection(qintptr socketDescriptor) {
    ClientThread *thread = new ClientThread(socketDescriptor, this);
    connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));
    connect(this, &Server::signalFor_PT_msg_answert, thread , &ClientThread::slot_msg_answer);
    connect(thread, &ClientThread::signal_for_Server_request_msg, this, &Server::slot_request_msg);
    thread->start();

    QTimer *timer = new QTimer(this);
    connect(timer, SIGNAL(timeout()), thread, SLOT(slot_msg_answer()));
    timer->start(2000);
}

All above code is based on Qt's threaded fortune server example, which is under bsd licence:

/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the examples of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:BSD$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** BSD License Usage
** Alternatively, you may use this file under the terms of the BSD license
** as follows:
**
** "Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are
** met:
**   * Redistributions of source code must retain the above copyright
**     notice, this list of conditions and the following disclaimer.
**   * Redistributions in binary form must reproduce the above copyright
**     notice, this list of conditions and the following disclaimer in
**     the documentation and/or other materials provided with the
**     distribution.
**   * Neither the name of The Qt Company Ltd nor the names of its
**     contributors may be used to endorse or promote products derived
**     from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
**
** $QT_END_LICENSE$
**
****************************************************************************/
AAEM
  • 1,837
  • 2
  • 18
  • 26
user2567875
  • 482
  • 4
  • 21
  • have you had a look at this? http://doc.qt.io/qt-5/threads-qobject.html especially the part with the event loops. – Hayt Nov 09 '16 at 16:20
  • Yes I did read it, and understood it that way that using "exec();" in the "run()" starts the "local" eventloop for the thread, and not using an explicit connectiontype on "connect(...);" makes qt choose the right connection by itself (default: qtautoconnection). – user2567875 Nov 09 '16 at 16:37
  • `QThread` is more like a thread controller, so unless you want to change how Qt manages threads, you're better off not inheriting from it. [This article](https://mayaposch.wordpress.com/2011/11/01/how-to-really-truly-use-qthreads-the-full-explanation/) describes a great method of how to really use `QThread`. – TheDarkKnight Nov 09 '16 at 17:30
  • 1
    @TheDarkKnight: Thanks for the link to the article, that helped a lot – user2567875 Nov 12 '16 at 21:47

1 Answers1

1

Your thread object has slots. Those slots will be called in the context of the thread that "own" the object unless Qt::DirectConnection forces a call in the thread that emits the signal.

Your ClientThread objects are "owned" by the main threadm (it executed the constructor of the class).

If you want to have those slots called in the thread running the client connection, you have to move the object into that thread.

Which means in your case the best option is to not derive from QThread at all but create your client handler as a QObject subclass and simply "move" it to a new QThread instances, see QObject::moveToThread()

As a bonus point you can test this without any secondary thread being involved.

Kevin Krammer
  • 5,159
  • 2
  • 9
  • 22
  • Thank you for the answer, together with the article pointed out above by TheDarkKnight I was able to understand it a bit further – user2567875 Nov 12 '16 at 21:50
  • I'm not sure this is correct, you can accomplish interthread signalling with out moving stuff from one thread to another in QT, as QT has queued connections now. – Krupip Oct 26 '18 at 18:31