Qt TCP通信

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Qt TCP通信

遇安啊   2022-09-29 我要评论

一、tcp介绍

TCP是面向连接的可靠传输的协议,协议规定通信的双方是服务端和客户端的两个角色:
服务端:负责监听网络端口,等待客户端的连接,用连接的socket完成信息的交互;
客户端:负责每次连接的发起,建立连接后才可以进行通信;

二、界面设计

服务器端

客户端

三、具体程序设计

(1)服务器端设计

1、建立一个工程,工程名为tcpserver,类名为server。在.pro文件中加入如下代码并保存。

QT       += network

2、进入server.h,添加类的前置声明

class QTcpServer;   //QTcpServer类的前置声明
class QTcpSocket;   //QTcpSocket类的前置声明

添加私有对象指针

QTcpServer *tcpServer;          //添加QTcpServer私有对象指针
QTcpSocket *socket;             //添加QTcpSocket私有对象指针

添加私有槽声明

 void tcpServer_connect();       //连接函数
 void read_data();               //读取从client发来的信息
 void disconnected();            //断开连接
 void on_sendButton_clicked();   //发送数据函数

3、转到server.cpp文件中

添加头文件#include,然后编写构造函数构造函数

Server::Server(QWidget *parent) :            //构造函数
    QDialog(parent),
    ui(new Ui::Server)
{
    ui->setupUi(this);
    tcpServer = new QTcpServer(this);                                             //创建对象
    if(!tcpServer->listen(QHostAddress::LocalHost,6666))                          //调用listen监听到来的连接,一旦有客户端连接到服务器,就发射newConnection信号
    {
        qDebug()<<tcpServer->errorString();
        close();
    }
    ui->sendButton->setEnabled(false);                                            // 设置按钮初始值值为false状态,即不可用
    connect(tcpServer,&QTcpServer::newConnection,this,&Server::tcpServer_connect);//将newConnection信号与槽函数连接起来
}

槽函数

//发送数据槽函数
void Server::on_sendButton_clicked()
{
    socket->write(ui->sendText->toPlainText().toLocal8Bit());      //通过write函数发送数据
    socket->flush();
    ui->sendText->clear();
}

//确认连接
void Server::tcpServer_connect()
{
    socket=tcpServer->nextPendingConnection();
    QObject::connect(socket,&QTcpSocket::readyRead,this,&Server::read_data);    //当接收缓冲区有信号到来时,产生readyRead信号
    QObject::connect(socket,&QTcpSocket::disconnected,this,&Server::disconnected);//当接收到dinconnected信号时,执行disconnected函数
    ui->sendButton->setEnabled(true);          //按钮设置为有效
    ui->label->setText(tr("连接成功!"));
}

//读取客户端发送的数据
void Server::read_data()
{
    QByteArray buffer=socket->readAll();           //读取的数据放入QByteArray对象中
    ui->recText->append(QString::fromLocal8Bit(buffer));       //将数据显示出来
}

void Server::disconnected()
{
    ui->sendButton->setEnabled(false);        //断开连接后按钮值设置为无效
}

(2)客户端设计

1、建立一个工程,工程名为tcpclient,类名为client。在.pro文件中加入如下代码并保存。

QT       += network

2、进入client.h,添加类的前置声明

class QTcpSocket;     //QTcpSocket类的前置声明

定义一个套接字对象指针

QTcpSocket *tcpSocket;       //定义一个套接字对象指针

添加私有槽函数声明

 void readData();                 //读取函数
 void discon();                   //断开连接
 void on_connectButton_clicked(); //连接按钮槽函数
 void on_sendButton_clicked();    //发送按钮槽函数

3、转到client.cpp,

添加头文件#include,并编写构造函数

Client::Client(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Client)
{
    ui->setupUi(this);
    tcpSocket = new QTcpSocket(this);          //定义套接字对象

    //关联信号到自定义的槽上
    QObject::connect(tcpSocket,&QTcpSocket::readyRead,this,&Client::readData);          //有接收数据时,执行读函数
    QObject::connect(tcpSocket,&QTcpSocket::disconnected,this,&Client::discon);
    ui->sendButton->setEnabled(false);
}

槽函数

void Client::discon()
{
    ui->sendButton->setEnabled(false);
    ui->connectButton->setText(tr("取消连接"));

}

//点击连接按钮,开始创建连接
void Client::on_connectButton_clicked()
{
    if(ui->connectButton->text()==tr("连接"))
    {
        tcpSocket->abort();
        tcpSocket->connectToHost(ui->hostLineEdit->text(),ui->portLineEdit->text().toInt());//连接到指定主机的端口
        if(!tcpSocket->waitForConnected(30000))                                             //超时连接失败
        {
            qDebug()<<"Connection failed!";
            return;
        }
        qDebug()<<"Connection successfully!";
        ui->connectButton->setText("取消连接");
        ui->sendButton->setEnabled(true);
    }
    else
    {
        tcpSocket->disconnectFromHost();
        ui->connectButton->setText("连接");
        ui->sendButton->setEnabled(false);
    }
}

//点击发送数据
void Client::on_sendButton_clicked()
{
    QString sendData=ui->sendText->toPlainText();                                           //发送数据为文本框的的内容
    tcpSocket->write(sendData.toLocal8Bit());
    tcpSocket->flush();
    ui->sendText->clear();
}

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们