Qt工作笔记-多线程时间服务应用
生活随笔
收集整理的這篇文章主要介紹了
Qt工作笔记-多线程时间服务应用
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
當(dāng)有客戶請(qǐng)求到達(dá)時(shí),服務(wù)器將啟動(dòng)一個(gè)新的進(jìn)程為它返回當(dāng)前時(shí)間,服務(wù)完畢后這個(gè)線程將自動(dòng)退出。
運(yùn)行截圖如下:
服務(wù)端:
dialog.h
#ifndef DIALOG_H #define DIALOG_H#include <QDialog> #include <QLabel> #include <QPushButton> class TimeServer; class Dialog : public QDialog {Q_OBJECTpublic:Dialog(QWidget *parent = 0);~Dialog(); public slots:void slotShow(); private:QLabel *Label1;QLabel *Label2;QPushButton *quitBtn;TimeServer *timeServer;int count; };#endif // DIALOG_Htimeserver.h
#ifndef TIMESERVER_H #define TIMESERVER_H#include <QObject> #include <QTcpServer>class Dialog;class TimeServer : public QTcpServer {Q_OBJECT public:TimeServer(QObject *parent=0); protected:void incomingConnection(int socketDescriptor); private:Dialog *dlg; };#endif // TIMESERVER_Htimethread.h
#ifndef TIMETHREAD_H #define TIMETHREAD_H #include <QObject> #include <QThread> #include <QTcpSocket> class TimeThread : public QThread { Q_OBJECT public: TimeThread(int socketDescriptor,QObject *parent=0); void run(); signals: void error(QTcpSocket::SocketError socketError); private: int socketDescriptor; }; #endif // TIMETHREAD_Hdialog.cpp
#include "dialog.h" #include <QHBoxLayout> #include <QVBoxLayout> #include <QMessageBox> #include "timeserver.h"Dialog::Dialog(QWidget *parent): QDialog(parent) {setWindowTitle(tr("多線程時(shí)間服務(wù)器"));Label1 =new QLabel(tr("服務(wù)器端口:"));Label2 = new QLabel;quitBtn = new QPushButton(tr("退出"));QHBoxLayout *BtnLayout = new QHBoxLayout;BtnLayout->addStretch(1);BtnLayout->addWidget(quitBtn);BtnLayout->addStretch(1);QVBoxLayout *mainLayout = new QVBoxLayout(this);mainLayout->addWidget(Label1);mainLayout->addWidget(Label2);mainLayout->addLayout(BtnLayout);connect(quitBtn,SIGNAL(clicked()),this,SLOT(close()));count=0;timeServer = new TimeServer(this);if(!timeServer->listen()){QMessageBox::critical(this,tr("多線程時(shí)間服務(wù)器"),tr("無(wú)法啟動(dòng)服務(wù)器:%1.").arg(timeServer->errorString()));close();return;}Label1->setText(tr("服務(wù)器端口:%1.").arg(timeServer->serverPort())); }Dialog::~Dialog() {}void Dialog::slotShow() {Label2->setText(tr("第%1次請(qǐng)求完畢。").arg(++count)); }main.cpp
#include "dialog.h" #include <QApplication>int main(int argc, char *argv[]) {QApplication a(argc, argv);Dialog w;w.show();return a.exec(); }timeserver.cpp
#include "timeserver.h" #include "timethread.h" #include "dialog.h"TimeServer::TimeServer(QObject *parent):QTcpServer(parent) {dlg =(Dialog *)parent; }void TimeServer::incomingConnection(int socketDescriptor) {TimeThread *thread = new TimeThread(socketDescriptor,0);connect(thread,SIGNAL(finished()),dlg,SLOT(slotShow()));connect(thread,SIGNAL(finished()),thread,SLOT(deleteLater()),Qt::DirectConnection);thread->start(); }timethread.cpp
#include "timethread.h" #include <QDateTime> #include <QByteArray> #include <QDataStream>TimeThread::TimeThread(int socketDescriptor,QObject *parent):QThread(parent),socketDescriptor(socketDescriptor) { }void TimeThread::run() {QTcpSocket tcpSocket;if(!tcpSocket.setSocketDescriptor(socketDescriptor)){emit error(tcpSocket.error());return;}QByteArray block;QDataStream out(&block,QIODevice::WriteOnly);out.setVersion(QDataStream::Qt_4_3);uint time2u = QDateTime::currentDateTime().toTime_t();out<<time2u;tcpSocket.write(block);tcpSocket.disconnectFromHost();tcpSocket.waitForDisconnected(); }客戶端:
timeclient.h
#ifndef TIMECLIENT_H #define TIMECLIENT_H#include <QDialog> #include <QLabel> #include <QLineEdit> #include <QPushButton> #include <QDateTimeEdit> #include <QTcpSocket> #include <QAbstractSocket> #include <QTimerEvent>class TimeClient : public QDialog {Q_OBJECTpublic:TimeClient(QWidget *parent = 0);~TimeClient();virtual void timerEvent(QTimerEvent *event);public slots:void enableGetBtn();void getTime();void readTime();void showError(QAbstractSocket::SocketError socketError);private:QLabel *serverNameLabel;QLineEdit *serverNameLineEdit;QLabel *portLabel;QLineEdit *portLineEdit;QDateTimeEdit *dateTimeEdit;QLabel *stateLabel;QPushButton *getBtn;QPushButton *quitBtn;uint time2u;QTcpSocket *tcpSocket;int m_timerId;bool startRun; };#endif // TIMECLIENT_Hmain.cpp
#include "timeclient.h" #include <QApplication>int main(int argc, char *argv[]) {QApplication a(argc, argv);TimeClient w;w.show();return a.exec(); }timeclient.cpp
#include "timeclient.h" #include <QHBoxLayout> #include <QVBoxLayout> #include <QGridLayout> #include <QDataStream> #include <QMessageBox>TimeClient::TimeClient(QWidget *parent): QDialog(parent) {setWindowTitle(tr("多線程時(shí)間服務(wù)客戶端"));serverNameLabel =new QLabel(tr("服務(wù)器名:"));serverNameLineEdit = new QLineEdit("Localhost");portLabel =new QLabel(tr("端口:"));portLineEdit = new QLineEdit;QGridLayout *layout = new QGridLayout;layout->addWidget(serverNameLabel,0,0);layout->addWidget(serverNameLineEdit,0,1);layout->addWidget(portLabel,1,0);layout->addWidget(portLineEdit,1,1);dateTimeEdit = new QDateTimeEdit(this);QHBoxLayout *layout1 = new QHBoxLayout;layout1->addWidget(dateTimeEdit);stateLabel =new QLabel(tr("請(qǐng)首先運(yùn)行時(shí)間服務(wù)器!"));QHBoxLayout *layout2 = new QHBoxLayout;layout2->addWidget(stateLabel);getBtn = new QPushButton(tr("獲取時(shí)間"));getBtn->setDefault(true);getBtn->setEnabled(false);quitBtn = new QPushButton(tr("退出"));QHBoxLayout *layout3 = new QHBoxLayout;layout3->addStretch();layout3->addWidget(getBtn);layout3->addWidget(quitBtn);QVBoxLayout *mainLayout = new QVBoxLayout(this);mainLayout->addLayout(layout);mainLayout->addLayout(layout1);mainLayout->addLayout(layout2);mainLayout->addLayout(layout3);connect(serverNameLineEdit,SIGNAL(textChanged(QString)),this,SLOT(enableGetBtn()));connect(portLineEdit,SIGNAL(textChanged(QString)),this,SLOT(enableGetBtn()));connect(getBtn,SIGNAL(clicked()),this,SLOT(getTime()));connect(quitBtn,SIGNAL(clicked()),this,SLOT(close()));tcpSocket = new QTcpSocket(this);connect(tcpSocket,SIGNAL(readyRead()),this,SLOT(readTime()));connect(tcpSocket,SIGNAL(error(QAbstractSocket::SocketError)),this,SLOT(showError(QAbstractSocket::SocketError)));portLineEdit->setFocus();m_timerId=startTimer(1000);startRun=false; }void TimeClient::timerEvent(QTimerEvent *event){if(event->timerId()==m_timerId && startRun){getTime();} }TimeClient::~TimeClient() {}void TimeClient::enableGetBtn() {getBtn->setEnabled(!serverNameLineEdit->text().isEmpty()&&!portLineEdit->text().isEmpty()); }void TimeClient::getTime() {getBtn->setEnabled(false);startRun=true;time2u =0;tcpSocket->abort();tcpSocket->connectToHost(serverNameLineEdit->text(),portLineEdit->text().toInt()); }void TimeClient::readTime() {QDataStream in(tcpSocket);in.setVersion(QDataStream::Qt_4_3);if(time2u==0){if(tcpSocket->bytesAvailable()<(int)sizeof(uint))return;in>>time2u;}dateTimeEdit->setDateTime(QDateTime::fromTime_t(time2u));getBtn->setEnabled(true); }void TimeClient::showError(QAbstractSocket::SocketError socketError) {switch (socketError){case QAbstractSocket::RemoteHostClosedError:break;case QAbstractSocket::HostNotFoundError:QMessageBox::information(this, tr("時(shí)間服務(wù)客戶端"),tr("主機(jī)不可達(dá)!"));break;case QAbstractSocket::ConnectionRefusedError:QMessageBox::information(this, tr("時(shí)間服務(wù)客戶端"),tr("連接被拒絕!"));break;default:QMessageBox::information(this, tr("時(shí)間服務(wù)客戶端"),tr("產(chǎn)生如下錯(cuò)誤: %1.").arg(tcpSocket->errorString()));}getBtn->setEnabled(true); }總結(jié)
以上是生活随笔為你收集整理的Qt工作笔记-多线程时间服务应用的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: Qt工作笔记-QTreeWidget中调
- 下一篇: C++ opengl 纹理生成