使用TCP进行网络通讯,只是个简单的demo,如图
服务器
客户端
主要用到的类
1-QNetworkConfigurationManager
2-QNetworkSession
3-QNetworkConfiguration
4-QSettings
5-QTcpServer
6-QTcpSocket
7-QMutex
8-QWaitCondition
9-QDataStream
QNetworkConfigurationManager可以保存之前的网络配置,可能实战需要细致研究,
这个线程实现的客户端还是写的有学习的地方,比如QDataStream初始化QTcpSocket的操作,以前没见过。
#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]
}