Qt文档阅读笔记-Threaded Fortune Server Example解析
生活随笔
收集整理的這篇文章主要介紹了
Qt文档阅读笔记-Threaded Fortune Server Example解析
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Fortune服務端展示了如何去創建一個多線程服務端。此實例與Fortune客戶端運行。
?首先繼承QTcpServer重寫下子類,方便實現多線程。
這里需要兩個類:一個是QTcpServer的子類,一個是QThread的子類
class FortuneServer : public QTcpServer{Q_OBJECTpublic:FortuneServer(QObject *parent = 0);protected:void incomingConnection(qintptr socketDescriptor) override;private:QStringList fortunes;};重寫了QTcpServer的QTcpServer::incomingConnection(),使用list存儲服務端需要返回的字符串:
FortuneServer::FortuneServer(QObject *parent): QTcpServer(parent){fortunes << tr("You've been leading a dog's life. Stay off the furniture.")<< tr("You've got to think about tomorrow.")<< tr("You will be surprised by a loud noise.")<< tr("You will feel hungry again in another hour.")<< tr("You might have mail.")<< tr("You cannot kill time without injuring eternity.")<< tr("Computers are not intelligent. They only think they are.");}QTcpServer::incomingConnection()中有個socketDescriptor參數,表示元素套接字描述符。這里FortuneThread有3個參數,一個是套接字描述符,一個是發送給客戶端的字符串,還有個是傳入的指向父節點的指針,并且關聯了信號和槽,當線程完成后現在會被指定釋放,使用start()運行。
void FortuneServer::incomingConnection(qintptr socketDescriptor){QString fortune = fortunes.at(QRandomGenerator::global()->bounded(fortunes.size()));FortuneThread *thread = new FortuneThread(socketDescriptor, fortune, this);connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));thread->start();}FortuneThread繼承了QThread,重寫了run方法,業務功能是操作被對應的socket。并且有個錯誤信號:
class FortuneThread : public QThread{Q_OBJECTpublic:FortuneThread(int socketDescriptor, const QString &fortune, QObject *parent);void run() override;signals:void error(QTcpSocket::SocketError socketError);private:int socketDescriptor;QString text;};Fortune構造函數:
FortuneThread::FortuneThread(int socketDescriptor, const QString &fortune, QObject *parent): QThread(parent), socketDescriptor(socketDescriptor), text(fortune){}下面是run方法,首先創建一個QTcpSocket,然后設置socketDescriptor,用于操作本地套接字。
void FortuneThread::run(){QTcpSocket tcpSocket;if (!tcpSocket.setSocketDescriptor(socketDescriptor)) {emit error(tcpSocket.error());return;}隨后構造數據:
QByteArray block;QDataStream out(&block, QIODevice::WriteOnly);out.setVersion(QDataStream::Qt_4_0);out << text;最后進行TCP的分手:
tcpSocket.write(block);tcpSocket.disconnectFromHost();tcpSocket.waitForDisconnected();}總結
以上是生活随笔為你收集整理的Qt文档阅读笔记-Threaded Fortune Server Example解析的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Java笔记-对称加密AES的使用
- 下一篇: Node.js笔记-使用socket.i