QT实现tcp客户端服务器通信

QT实现tcp客户端服务器通信_第1张图片

 最终实现效果如上图

服务器端代码

tcpwidget.cpp代码

#include "tcpwidget.h"
#include "ui_tcpwidget.h"

TcpWidget::TcpWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::TcpWidget)
{
    ui->setupUi(this);

    //初始化服务器的对象
    server = new QTcpServer(this);

    //进入监听状态
#if 1
    server->listen(QHostAddress::Any, ui->portEdit->text().toUShort());
#else
    server->listen(QHostAddress(ui->ipEdit->text()), ui->portEdit->text().toUShort());
#endif

    //如果客户端连接后,那么会自动触发newConnection信号,在槽方法里需要接收客户端的链接
    QObject::connect(server, SIGNAL(newConnection()),
                     this,  SLOT(connectSlot()));
}

void TcpWidget::connectSlot()
{
    ui->recvEdit->setText("有新的连接过来");
    //接收客户端的连接
    client = server->nextPendingConnection();

    //客户端一旦发数据,就会触发readyRead信号,那么只需要接到这个信号后,读取内容即可
    QObject::connect(client, SIGNAL(readyRead()),
                     this,  SLOT(readSlot()));
}

void TcpWidget::readSlot()
{
    //业务逻辑
    QByteArray buf = client->readAll();

    //显示到界面上
    QString str = QString::fromLocal8Bit(buf);
    ui->recvEdit->setText(str);
}

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

void TcpWidget::on_pushButton_clicked()
{
    QString str = ui->sendEdit->toPlainText();
    client->write(str.toLocal8Bit());
}

main.cpp

#include "tcpwidget.h"
#include 

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    TcpWidget w;
    w.show();

    return a.exec();
}

客户端代码

clientwidget.cpp代码

#include "clientwidget.h"
#include "ui_clientwidget.h"

ClientWidget::ClientWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::ClientWidget)
{
    ui->setupUi(this);

    //1.实例化客户端的对象
    client = new QTcpSocket(this);
}

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

void ClientWidget::on_connectBtn_clicked()
{
    //2.连接到服务器
    client->connectToHost(QHostAddress(ui->ipEdit->text()),\
                          ui->portEdit->text().toUShort());

    if (client->waitForConnected(1000)){
        ui->recvEdit->setText("connect success");
    }else{
        qDebug()<<"connect failed";
    }

    //3.绑定readyread()信号
    QObject::connect(client, SIGNAL(readyRead()),
                     this,  SLOT(readSlot()));
}

/**
 * @brief 把发送框中内容发给服务器
 */
void ClientWidget::on_sendBtn_clicked()
{
    QString buf = ui->sendEdit->text();
    QByteArray sendBuf = buf.toUtf8();

    client->write(sendBuf);
}

/**
 * @brief 读取来自服务器的数据
 */
void ClientWidget::readSlot()
{
    //6.读取数据,显示到界面
    QByteArray buf = client->readAll();
    ui->recvEdit->setText(QString(buf));
}

main.cpp

#include "clientwidget.h"
#include 

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    ClientWidget w;
    w.show();

    return a.exec();
}

你可能感兴趣的:(服务器)