<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Keep connection opened for a QThreaded QTcpSocket]]></title><description><![CDATA[<p dir="auto">Hello,<br />
I have adapted the <a href="https://doc.qt.io/qt-6/qtnetwork-blockingfortuneclient-example.html" target="_blank" rel="noopener noreferrer nofollow ugc">Blocking Fortune Client Example</a>. Here is the code:</p>
<p dir="auto"><strong>connectionthread.h</strong></p>
<pre><code>#ifndef CONNECTIONTHREAD_H
#define CONNECTIONTHREAD_H

#include &lt;QThread&gt;
#include &lt;QMutex&gt;
#include &lt;QWaitCondition&gt;

class ConnectionThread : public QThread
{
    Q_OBJECT

public:
    ConnectionThread(QObject *parent = nullptr);
    ~ConnectionThread();

    void requestNewData(const QString &amp;hostName, quint16 port, const QString &amp;message);
    void run() override;

signals:
    void newData(const QByteArray &amp;data);
    void error(int socketError, const QString &amp;message);

private:
    QString m_hostName;
    quint16 m_port;
    QString m_message;
    QMutex m_mutex;
    QWaitCondition m_cond;
    bool m_quit;
};

#endif // CONNECTIONTHREAD_H
</code></pre>
<p dir="auto"><strong>connectionthread.cpp</strong></p>
<pre><code>#include &lt;QtNetwork&gt;

#include "connectionthread.h"

ConnectionThread::ConnectionThread(QObject *parent)
    : QThread(parent), m_quit(false)
{
}

ConnectionThread::~ConnectionThread()
{
    m_mutex.lock();
    m_quit = true;
    m_cond.wakeOne();
    m_mutex.unlock();
    wait();
}

void ConnectionThread::requestNewData(const QString &amp;hostName, quint16 port, const QString &amp;message)
{
    QMutexLocker locker(&amp;m_mutex);
    m_hostName = hostName;
    m_port = port;
    m_message = message;

    if (!isRunning())
        start();
    else
        m_cond.wakeOne();
}
void ConnectionThread::run()
{
    m_mutex.lock();

    QString serverName = m_hostName;
    quint16 serverPort = m_port;
    m_mutex.unlock();

    while (!m_quit) {
        const int Timeout = 3 * 1000; // 3 sec.

        QTcpSocket socket;
        socket.connectToHost(serverName, serverPort);

        if (!socket.waitForConnected(Timeout)) {
            emit error(socket.error(), socket.errorString());
            return;
        }

        qDebug() &lt;&lt; tr("Sending %1 to the server").arg(m_message);
        socket.write(m_message.toUtf8());


        QByteArray data;
        if (!socket.waitForReadyRead(Timeout)) {
            emit error(socket.error(), socket.errorString());
            return;
        }
        data = socket.readAll();

        m_mutex.lock();
        emit newData(data);

        m_cond.wait(&amp;m_mutex);
        serverName = m_hostName;
        serverPort = m_port;
        m_mutex.unlock();
    }
}
</code></pre>
<p dir="auto">In the main code, I connect the thread with</p>
<pre><code>ConnectionThread m_thread;

connect(&amp;m_thread, &amp;ConnectionThread::newData,
        this, &amp;Client::readData);

connect(&amp;m_thread, &amp;ConnectionThread::error,
        this, &amp;Client::displayError);

m_thread.requestNewData(m_ip_address, m_port, m_messages[m_msgidC2]);

...

</code></pre>
<p dir="auto">It works well so far. Yet, now I need to keep the connection opened, i.e. not reconnect, each time I send a new message (with requestNewData())</p>
<p dir="auto">I do not know how to modify my code to achieve that.</p>
<p dir="auto">What I tried is to define the socket as a member of ConnectionThread. Then in the run() function, I call   socket.connectToHost() only if  socket.state() is not equal QTcpSocket::connected.</p>
<p dir="auto">But doing so, I get message like this one<br />
<em>QObject: Cannot create children for a parent that is in a different thread.<br />
(Parent is QTcpSocket(0x559b0576ae30), parent's thread is QThread(0x559b04f23660), current thread is ConnectionThread(0x559b05582b40)</em></p>
<p dir="auto">Any idea of design?</p>
]]></description><link>https://forum.qt.io/topic/139781/keep-connection-opened-for-a-qthreaded-qtcpsocket</link><generator>RSS for Node</generator><lastBuildDate>Thu, 05 Nov 2026 07:55:31 GMT</lastBuildDate><atom:link href="https://forum.qt.io/topic/139781.rss" rel="self" type="application/rss+xml"/><pubDate>Tue, 04 Oct 2022 09:53:29 GMT</pubDate><ttl>60</ttl><item><title><![CDATA[Reply to Keep connection opened for a QThreaded QTcpSocket on Tue, 04 Oct 2022 12:44:21 GMT]]></title><description><![CDATA[<p dir="auto"><a class="plugin-mentions-user plugin-mentions-a" href="/user/jsulm">@<bdi>jsulm</bdi></a> said in <a href="/post/731265">Keep connection opened for a QThreaded QTcpSocket</a>:</p>
<blockquote>
<p dir="auto"><a class="plugin-mentions-user plugin-mentions-a" href="/user/odelaune">@<bdi>odelaune</bdi></a> said in <a href="/post/731256">Keep connection opened for a QThreaded QTcpSocket</a>:</p>
<blockquote>
<p dir="auto">while (!m_quit) {<br />
const int Timeout = 3 * 1000; // 3 sec.</p>
<pre><code>    QTcpSocket socket;
    socket.connectToHost(serverName, serverPort);
</code></pre>
</blockquote>
<p dir="auto">Why do you create a new socket on each loop iteration?<br />
Create it once before the loop and also connect before you enter the loop.<br />
Also, all variables needed in the thread should be created inside run() (not as class member). Because only what is created inside run() is inside the thread.</p>
</blockquote>
<p dir="auto">For now, I tried to move this code snippet</p>
<pre><code>    const int Timeout = 3 * 1000; // 3 sec.

    QTcpSocket socket;
    socket.connectToHost(serverName, serverPort);

    if (!socket.waitForConnected(Timeout)) {
        emit error(socket.error(), socket.errorString());
        return;
    }
</code></pre>
<p dir="auto">just before the while loop. Yet, doing so, the first message is well sent (it is received by the server), but when I want to send another message (after the first one), I always exit the while loop because I always enter into <em>if (!socket.waitForReadyRead(Timeout))</em>. Actually, the server never receive the second request.<br />
So something is probably still missing in the code.</p>
<p dir="auto">For now, I do not understand why the second message is not sent. I have checked what the write functions return and it corresponds to the correct number of bytes that are sent. But the server does not receive anything...</p>
<p dir="auto">If I place the code snippet inside the while loop, all messages are correctly sent...</p>
]]></description><link>https://forum.qt.io/post/731273</link><guid isPermaLink="true">https://forum.qt.io/post/731273</guid><dc:creator><![CDATA[odelaune]]></dc:creator><pubDate>Tue, 04 Oct 2022 12:44:21 GMT</pubDate></item><item><title><![CDATA[Reply to Keep connection opened for a QThreaded QTcpSocket on Tue, 04 Oct 2022 11:06:19 GMT]]></title><description><![CDATA[<p dir="auto"><a class="plugin-mentions-user plugin-mentions-a" href="/user/odelaune">@<bdi>odelaune</bdi></a> said in <a href="/post/731256">Keep connection opened for a QThreaded QTcpSocket</a>:</p>
<blockquote>
<p dir="auto">while (!m_quit) {<br />
const int Timeout = 3 * 1000; // 3 sec.</p>
<pre><code>    QTcpSocket socket;
    socket.connectToHost(serverName, serverPort);
</code></pre>
</blockquote>
<p dir="auto">Why do you create a new socket on each loop iteration?<br />
Create it once before the loop and also connect before you enter the loop.<br />
Also, all variables needed in the thread should be created inside run() (not as class member). Because only what is created inside run() is inside the thread.</p>
]]></description><link>https://forum.qt.io/post/731265</link><guid isPermaLink="true">https://forum.qt.io/post/731265</guid><dc:creator><![CDATA[jsulm]]></dc:creator><pubDate>Tue, 04 Oct 2022 11:06:19 GMT</pubDate></item></channel></rss>