您的位置:首页 > 理论基础 > 计算机网络

Qt实现简单的TCP网络电子词典(带界面,能并发)

2017-04-25 23:13 706 查看
服务器代码:

#include "dialog.h"

Dialog::Dialog(QWidget *parent)

    : QDialog(parent)

{

    tcpServer=new QTcpServer(this);

    tcpServer->listen(QHostAddress::Any,6677);

    connect(tcpServer,SIGNAL(newConnection()),this,SLOT(newClient()));

    QSqlDatabase db=QSqlDatabase::addDatabase("QSQLITE");

    db.setDatabaseName("my.db");

    db.open();

}

Dialog::~Dialog()

{

}

void Dialog::newClient()

{

    nextBlockSize=0;

    QTcpSocket *tcpSocket=tcpServer->nextPendingConnection();

    connect(tcpSocket,SIGNAL(readyRead()),this,SLOT(readClient()));

    connect(tcpSocket,SIGNAL(disconnected()),tcpSocket,SLOT(deleteLater()));

}

void Dialog::readClient()

{

    QTcpSocket *tcpSocket=qobject_cast<QTcpSocket*>(sender());

    QDataStream in(tcpSocket);

    if(nextBlockSize==0) {

        if(tcpSocket->bytesAvailable() < sizeof(quint16))

            return;

        in >> nextBlockSize;

    }

    if(tcpSocket->bytesAvailable() < nextBlockSize)

        return;

    quint8 type;

    QString username,password,word;

    in >> type;

    if(type!='Q') {

        in >> username >> password;

        processLogin(tcpSocket,type,username,password);

    }else {

        in >> word;

        processFind(tcpSocket,word);

    }

    tcpSocket->close();

}

void Dialog::processLogin(QTcpSocket *tcpSocket, quint8 type, QString &username, QString password)

{

    QByteArray buf;

    QDataStream out(&buf,QIODevice::WriteOnly);

    out << quint16(0) << quint8(type);

    QSqlQuery query("select * from users");

    QString user,pass;

    if(type=='L') {

        while(query.next()) {

            user=query.value(0).toString();

            pass=query.value(1).toString();

            if((user == username) && (pass == password)) {

                out << QString("OK");

                out.device()->seek(0);

                tcpSocket->write(buf);

                return;

            }

        }

        out << QString("Failed");

        out.device()->seek(0);

        tcpSocket->write(buf);

    }

    else if(type=='R') {

        while(query.next()) {

            user=query.value(0).toString();

            if(user == username) {

                out << QString("Failed");

                out.device()->seek(0);

                out << quint16(buf.size()-sizeof(quint16));

                tcpSocket->write(buf);

                return;

            }

        }

        query.exec(QString("insert into users values(\"%1\",\"%2\")").arg(username).arg(password));

        out << QString("OK");

        out.device()->seek(0);

        out << quint16(buf.size()-sizeof(quint16));

        tcpSocket->write(buf);

    }

}

void Dialog::processFind(QTcpSocket *tcpSocket, QString &word)

{

    QByteArray buf;

    QDataStream out(&buf,QIODevice::WriteOnly);

    out << quint16(0) << quint8('R');

    QFile file("dict.txt");

    if(!file.open(QIODevice::ReadOnly|QIODevice::Text)) {

        qDebug() << "open dict.txt failed";

        return;

    }

    QString line;

    QTextStream in(&file);

    while(!in.atEnd()) {

        line=in.readLine();

        if(line.startsWith(word)) {

            word=line.mid(word.length());

            word=word.trimmed();

            out << word;

            out.device()->seek(0);

            out << quint16(buf.size()-sizeof(quint16));

            tcpSocket->write(buf);

            return;

        }

    }

    word="<font color=red>word not found<font>";

    out << word;

    out.device()->seek(0);

    out << quint16(buf.size()-sizeof(quint16));

    tcpSocket->write(buf);

    return;

}

===============================================================================================================================

#include "logindialog.h"

#include "ui_logindialog.h"

LoginDialog::LoginDialog(QWidget *parent) :

    QDialog(parent),

    ui(new Ui::LoginDialog)

{

    ui->setupUi(this);

    tcpSocket=new QTcpSocket(this);

    connect(tcpSocket,SIGNAL(connected()),this,SLOT(sendRequest()));

    connect(tcpSocket,SIGNAL(readyRead()),this,SLOT(readResponse()));

}

LoginDialog::~LoginDialog()

{

    delete ui;

}

void LoginDialog::on_buttonBox_accepted()

{

    nextBlockSize=0;

    tcpSocket->connectToHost("127.0.0.1",6677);

}

void LoginDialog::readResponse()

{

    QDataStream in(tcpSocket);

    if(nextBlockSize==0) {

        if(tcpSocket->bytesAvailable() < sizeof(quint16))

            return;

        in >> nextBlockSize;

    }

    if(tcpSocket->bytesAvailable() < nextBlockSize)

        return;

    quint8 type;

    QString str;

    in >> type >> str;

    tcpSocket->close();

    if(type=='R' && str=="OK") {

        QMessageBox::information(this,"success","register OK");

    }else if(type=='R') {

        QMessageBox::warning(this,"error","register failed");

    }

    if(type=='L' && str=="OK") {

        FindDialog *dialog=new FindDialog;

        dialog->show();

        hide();

    }else if(type=='L') {

        QMessageBox::warning(this,"error","login error");

    }

}

void LoginDialog::sendRequest()

{

    QByteArray buf;

    QDataStream out(&buf,QIODevice::WriteOnly);

    out << quint16(0);

    if(ui->radioButton->isChecked())

        out << quint8('L');

    else

        out << quint8('R');

    out << ui->lineEdit->text() << ui->lineEdit_2->text();

    out.device()->seek(0);

    out << quint16(buf.size()-sizeof(quint16));

    tcpSocket->write(buf);

}

=================================================================================================================================

#include "finddialog.h"

#include "ui_finddialog.h"

FindDialog::FindDialog(QWidget *parent) :

    QDialog(parent),

    ui(new Ui::FindDialog)

{

    ui->setupUi(this);

    tcpSocket=new QTcpSocket(this);

    connect(tcpSocket,SIGNAL(readyRead()),this,SLOT(readResponse()));

    connect(tcpSocket,SIGNAL(connected()),this,SLOT(sendRequest()));

}

FindDialog::~FindDialog()

{

    delete ui;

}

void FindDialog::on_pushButton_clicked()

{

    tcpSocket->connectToHost("127.0.0.1",6677);

    nextBlockSize=0;

}

void FindDialog::sendRequest()

{

    QByteArray buf;

    QDataStream out(&buf,QIODevice::WriteOnly);

    out << quint16(0) << quint8('Q') << ui->lineEdit->text();

    out.device()->seek(0);

    out << quint16(buf.size()-sizeof(quint16));

    tcpSocket->write(buf);

}

void FindDialog::readResponse()

{

    QDataStream in(tcpSocket);

    if(nextBlockSize==0) {

        if(tcpSocket->bytesAvailable() < sizeof(quint16))

            return;

        in >> nextBlockSize;

    }

    if(tcpSocket->bytesAvailable() < nextBlockSize)

        return;

    quint8 type;

    QString str;

    in >> type >> str;

    if(type=='R')

        ui->textBrowser->setText(str);

    tcpSocket->close();

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: