QT學習之路六(QT的tcp傳輸)

  這幾天一直在做銀行的管理系統,包括職工的登陸註冊以及客戶的開戶轉賬存取款等功能,這幾天天天通宵也寫的差不多了,還剩下最後一個功能,交易記錄的管理,差不多明天應該就能結束了。

  這兩天爲了做這個東西,我把qt的網絡模塊初學了一下,學了一下qt的tcp傳輸,實現了服務器與客戶端的通信。但是,在做的時候,我本來是打算做一個循環併發的服務器,但測試了一下後,突然發現,這個服務器根本不用開線程,它一直在工作,在一個客戶端連接後,它就通過信號與槽函數,直接去處理,處理完後再返回,這樣做,在連接數少的時候,確實和併發服務器差不多,但是做一個假設,假設有1000多臺客戶端連接的話,瞬間崩潰了,但我也不懂在哪邊開線程合適,Linux中的話服務器在連接到後就應該開闢線程,但是qt中服務器在得到連接後直接去處理槽函數了,所以想了很久,還是不懂在哪邊開闢線程,最終還是沒有做出來,不過幾十臺的話處理起來應該沒有什麼問題(安慰自己。。)。

下面的代碼(沒有開線程):

/********************************************************************************
** Form generated from reading UI file 'client.ui'
**
** Created: Thu Feb 16 16:09:39 2017
**      by: Qt User Interface Compiler version 4.8.1
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/

#ifndef UI_CLIENT_H
#define UI_CLIENT_H

#include <QtCore/QVariant>
#include <QtGui/QAction>
#include <QtGui/QApplication>
#include <QtGui/QButtonGroup>
#include <QtGui/QDialog>
#include <QtGui/QHeaderView>
#include <QtGui/QLabel>
#include <QtGui/QLineEdit>
#include <QtGui/QPushButton>

QT_BEGIN_NAMESPACE

class Ui_client
{
public:
    QLabel *label;
    QLabel *label_2;
    QLabel *messagelabel;
    QLineEdit *hostlineEdit;
    QLineEdit *portlineEdit;
    QPushButton *connect;

    void setupUi(QDialog *client)
    {
        if (client->objectName().isEmpty())
            client->setObjectName(QString::fromUtf8("client"));
        client->resize(400, 300);
        label = new QLabel(client);
        label->setObjectName(QString::fromUtf8("label"));
        label->setGeometry(QRect(60, 70, 71, 31));
        label_2 = new QLabel(client);
        label_2->setObjectName(QString::fromUtf8("label_2"));
        label_2->setGeometry(QRect(60, 130, 71, 31));
        messagelabel = new QLabel(client);
        messagelabel->setObjectName(QString::fromUtf8("messagelabel"));
        messagelabel->setGeometry(QRect(80, 190, 171, 61));
        hostlineEdit = new QLineEdit(client);
        hostlineEdit->setObjectName(QString::fromUtf8("hostlineEdit"));
        hostlineEdit->setGeometry(QRect(130, 80, 113, 20));
        portlineEdit = new QLineEdit(client);
        portlineEdit->setObjectName(QString::fromUtf8("portlineEdit"));
        portlineEdit->setGeometry(QRect(130, 140, 113, 20));
        connect = new QPushButton(client);
        connect->setObjectName(QString::fromUtf8("connect"));
        connect->setGeometry(QRect(260, 240, 75, 23));

        retranslateUi(client);

        QMetaObject::connectSlotsByName(client);
    } // setupUi

    void retranslateUi(QDialog *client)
    {
        client->setWindowTitle(QApplication::translate("client", "client", 0, QApplication::UnicodeUTF8));
        label->setText(QApplication::translate("client", "\344\270\273\346\234\272", 0, QApplication::UnicodeUTF8));
        label_2->setText(QApplication::translate("client", "\347\253\257\345\217\243", 0, QApplication::UnicodeUTF8));
        messagelabel->setText(QApplication::translate("client", "\346\216\245\346\224\266\345\210\260\347\232\204\344\277\241\346\201\257", 0, QApplication::UnicodeUTF8));
        connect->setText(QApplication::translate("client", "\350\277\236\346\216\245", 0, QApplication::UnicodeUTF8));
    } // retranslateUi

};

namespace Ui {
    class client: public Ui_client {};
} // namespace Ui

QT_END_NAMESPACE

#endif // UI_CLIENT_H
#ifndef CLIENT_H
#define CLIENT_H

#include <QDialog>
#include <QAbstractSocket>
#include <QTcpSocket>
#include <QString>

namespace Ui {
class client;
}

class client : public QDialog
{
    Q_OBJECT
    
public:
    explicit client(QWidget *parent = 0);
    ~client();
    
private:
    Ui::client *ui;
    QTcpSocket *tcpsocket;
    QString  message;
    quint16 blocksize;
private slots:
    void newconnect();
    void readmessage();
    void displayreeoe(QAbstractSocket::SocketError);
    void on_connect_clicked();
};

#endif // CLIENT_H

#include "client.h"
#include "ui_client.h"
#include <QtNetwork>

client::client(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::client)
{
    ui->setupUi(this);
    tcpsocket = new QTcpSocket(this);
    connect(tcpsocket, SIGNAL(readyRead()), this, SLOT(readmessage()));
    connect(tcpsocket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(displayreeoe(QAbstractSocket::SocketError)));

}

client::~client()
{
    delete ui;
}

void client::newconnect()
{
    blocksize = 0;
    tcpsocket->abort();
    tcpsocket->connectToHost(ui->hostlineEdit->text(), ui->portlineEdit->text().toInt());
}

void client::readmessage()
{
    QDataStream in(tcpsocket);
    in.setVersion(QDataStream::Qt_4_6);
    if(blocksize == 0)
    {
        if(tcpsocket->bytesAvailable() < (int)sizeof(quint16))
        {
            return;
        }
        in>>blocksize;
    }
    if(tcpsocket->bytesAvailable() < blocksize)
    {
        return;
    }
    in>>message;
    ui->messagelabel->setText(message);
}

void client::displayreeoe(QAbstractSocket::SocketError)
{
    qDebug()<<tcpsocket->errorString();
}

void client::on_connect_clicked()
{
    newconnect();
}

#include <QtGui/QApplication>
#include "client.h"

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    client w;
    w.show();
    
    return a.exec();
}
/********************************************************************************
** Form generated from reading UI file 'server.ui'
**
** Created: Thu Feb 16 15:41:59 2017
**      by: Qt User Interface Compiler version 4.8.1
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/

#ifndef UI_SERVER_H
#define UI_SERVER_H

#include <QtCore/QVariant>
#include <QtGui/QAction>
#include <QtGui/QApplication>
#include <QtGui/QButtonGroup>
#include <QtGui/QDialog>
#include <QtGui/QHeaderView>
#include <QtGui/QLabel>

QT_BEGIN_NAMESPACE

class Ui_server
{
public:
    QLabel *label;

    void setupUi(QDialog *server)
    {
        if (server->objectName().isEmpty())
            server->setObjectName(QString::fromUtf8("server"));
        server->resize(400, 300);
        label = new QLabel(server);
        label->setObjectName(QString::fromUtf8("label"));
        label->setGeometry(QRect(70, 40, 121, 61));

        retranslateUi(server);

        QMetaObject::connectSlotsByName(server);
    } // setupUi

    void retranslateUi(QDialog *server)
    {
        server->setWindowTitle(QApplication::translate("server", "server", 0, QApplication::UnicodeUTF8));
        label->setText(QApplication::translate("server", "\347\255\211\345\276\205\350\277\236\346\216\245....", 0, QApplication::UnicodeUTF8));
    } // retranslateUi

};

namespace Ui {
    class server: public Ui_server {};
} // namespace Ui

QT_END_NAMESPACE

#endif // UI_SERVER_H

#ifndef SERVER_H
#define SERVER_H

#include <QDialog>
#include <QTcpServer>

namespace Ui {
class server;
}

class server : public QDialog
{
    Q_OBJECT
    
public:
    explicit server(QWidget *parent = 0);
    ~server();
    
private:
    Ui::server *ui;
    QTcpServer *tcp_server;
public slots:
    void sendmassage();
};

#endif // SERVER_H

#include "server.h"
#include "ui_server.h"
#include <QtNetwork>

server::server(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::server)
{
    ui->setupUi(this);
    tcp_server = new QTcpServer(this);
    if(! tcp_server->listen(QHostAddress::LocalHost, 6666))
    {
        qDebug()<<tcp_server->errorString();
        close();
    }
    connect(tcp_server, SIGNAL(newConnection()), this, SLOT(sendmassage()));
}

server::~server()
{
    delete ui;
}

void server::sendmassage()
{
    QByteArray block;
    QDataStream out(&block, QIODevice::WriteOnly);

    out.setVersion(QDataStream::Qt_4_0);
    out<<(quint16)0;
    out<<tr("hello tcp!!!");
    out.device()->seek(0);
    out<<(quint16)(block.size()-sizeof(quint16));

    QTcpSocket *cfd = tcp_server->nextPendingConnection();
    connect(cfd, SIGNAL(disconnected()), cfd, SLOT(deleteLater()));
    cfd->write(block);
    cfd->disconnectFromHost();
    ui->label->setText("send message successful!");
}

#include <QtGui/QApplication>
#include "server.h"

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    server w;
    w.show();
    
    return a.exec();
}




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章