05fc3aef53
Replace the current license disclaimer in files by a SPDX-License-Identifier. Files that have to be modified by hand are modified. License files are organized under LICENSES directory. Task-number: QTBUG-67283 Change-Id: Id880c92784c40f3bbde861c0d93f58151c18b9f1 Reviewed-by: Qt CI Bot <qt_ci_bot@qt-project.org> Reviewed-by: Lars Knoll <lars.knoll@qt.io> Reviewed-by: Jörg Bornemann <joerg.bornemann@qt.io>
91 lines
1.7 KiB
C++
91 lines
1.7 KiB
C++
// Copyright (C) 2016 The Qt Company Ltd.
|
|
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
|
|
|
|
#include <QtNetwork>
|
|
|
|
#include "fortunethread.h"
|
|
|
|
FortuneThread::FortuneThread(QObject *parent)
|
|
: QThread(parent), quit(false)
|
|
{
|
|
}
|
|
|
|
//! [0]
|
|
FortuneThread::~FortuneThread()
|
|
{
|
|
mutex.lock();
|
|
quit = true;
|
|
cond.wakeOne();
|
|
mutex.unlock();
|
|
wait();
|
|
}
|
|
//! [0]
|
|
|
|
//! [1] //! [2]
|
|
void FortuneThread::requestNewFortune(const QString &hostName, quint16 port)
|
|
{
|
|
//! [1]
|
|
QMutexLocker locker(&mutex);
|
|
this->hostName = hostName;
|
|
this->port = port;
|
|
//! [3]
|
|
if (!isRunning())
|
|
start();
|
|
else
|
|
cond.wakeOne();
|
|
}
|
|
//! [2] //! [3]
|
|
|
|
//! [4]
|
|
void FortuneThread::run()
|
|
{
|
|
mutex.lock();
|
|
//! [4] //! [5]
|
|
QString serverName = hostName;
|
|
quint16 serverPort = port;
|
|
mutex.unlock();
|
|
//! [5]
|
|
|
|
//! [6]
|
|
while (!quit) {
|
|
//! [7]
|
|
const int Timeout = 5 * 1000;
|
|
|
|
QTcpSocket socket;
|
|
socket.connectToHost(serverName, serverPort);
|
|
//! [6] //! [8]
|
|
|
|
if (!socket.waitForConnected(Timeout)) {
|
|
emit error(socket.error(), socket.errorString());
|
|
return;
|
|
}
|
|
//! [8] //! [11]
|
|
|
|
QDataStream in(&socket);
|
|
in.setVersion(QDataStream::Qt_4_0);
|
|
QString fortune;
|
|
//! [11] //! [12]
|
|
|
|
do {
|
|
if (!socket.waitForReadyRead(Timeout)) {
|
|
emit error(socket.error(), socket.errorString());
|
|
return;
|
|
}
|
|
|
|
in.startTransaction();
|
|
in >> fortune;
|
|
} while (!in.commitTransaction());
|
|
//! [12] //! [15]
|
|
|
|
mutex.lock();
|
|
emit newFortune(fortune);
|
|
//! [7]
|
|
|
|
cond.wait(&mutex);
|
|
serverName = hostName;
|
|
serverPort = port;
|
|
mutex.unlock();
|
|
}
|
|
//! [15]
|
|
}
|