日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Qt文档阅读笔记-Threaded Fortune Server Example解析

發布時間:2025/3/15 编程问答 29 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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解析的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。