目录
1、简介
2 、TCP通信流程
3、基于TCP通信所需要的类
4、QT端设计
4.1项目建立
4.2 TCP网络程序设计
4.2.1 QT界面设计
4.2.2 UI布局
4.2.3 控件重命名
5、widget.h
6、widget.c
1、简介
网络有TCP和UDP。本文主要通过QT完成TCP网络设计,通过ESP8266与单片机进行通讯。
2 、TCP通信流程
3、基于TCP通信所需要的类
QTcpSever 服务器类,用于监听客户端连接以及和客户端建立连接。
QTcpSocket 通信的套接字类,客户端、服务器端都需要使用。
QTcpSever、QTcpSocket都属于网络模块network。
4、QT端设计
4.1项目建立
1、
2、
3、
4、
5、
6、
7、
4.2 TCP网络程序设计
QT提供了QTcpServer类,可以直接实例化一个客户端,可在help中索引如下:
The QTcpServer class provides a TCP-based server. More...
Header: #include <QTcpServer>
qmake: QT += network
Inherits: QObject
首先在在.pro文件中添加QT += network才可以进行网络编程
QT += core gui network
接着在widget.h中添加所需头文件,头文件如下所示:
#include <QTcpServer>
#include <QTcpSocket>
#include <QNetworkInterface>
4.2.1 QT界面设计
如下所示:
1、
2、
3、
4、
5、
6、
4.2.2 UI布局
整体垂直布局
对于接收框设置成只读,如下所示:
4.2.3 控件重命名
5、widget.h
#ifndef WIDGET_H
#define WIDGET_H#include <QWidget>
#include <QTcpServer>
#include <QTcpSocket>
#include <QNetworkInterface>namespace Ui {
class Widget;
}class Widget : public QWidget
{Q_OBJECTpublic:explicit Widget(QWidget *parent = nullptr);~Widget();QTcpServer *tcpserver;//声明一个QTcpserver的对象,用于监听QTcpSocket *tcpsocket;//创建服务器的套接字,用于与客户端进行通信private slots:void newConnection_Slot();void readyRead_Slot();void on_open_Button_clicked();void on_close_Button_clicked();void on_send_Button_clicked();private:Ui::Widget *ui;
};#endif // WIDGET_H
6、widget.c
#include "widget.h"
#include "ui_widget.h"Widget::Widget(QWidget *parent) :QWidget(parent),ui(new Ui::Widget)
{ui->setupUi(this);tcpserver = new QTcpServer(this);tcpsocket = new QTcpSocket(this);//当服务器发现有人要来连接时,就会发出newconnection 的信号,从而触发槽函数newConnection_Slot()(自行编写的槽函数)connect(tcpserver,SIGNAL(newConnection()),this,SLOT(newConnection_Slot()));
}//建立接收客户端连接的槽函数,有人连接就触发这个槽函数
void Widget::newConnection_Slot()
{//获取这个服务器sserver与客户端通信的套接字tcpsocket = tcpserver->nextPendingConnection();connect(tcpsocket,SIGNAL(readyRead()),this,SLOT(readyRead_Slot()));
}void Widget::readyRead_Slot()
{QString buf;buf = tcpsocket->readAll();ui->rece_Edit->appendPlainText(buf);
}Widget::~Widget()
{delete ui;
}void Widget::on_open_Button_clicked()
{//服务端点击启动服务器,服务器就开始监听//监听----------启动服务器//QHostAddress::Any 地址,接纳所有的地址//端口号 ui->sportEdit->text()获得输入的字符串,转换成无符号短整型tcpserver->listen(QHostAddress::Any,ui->port_line->text().toUShort());
}void Widget::on_close_Button_clicked()
{tcpserver->close();
}void Widget::on_send_Button_clicked()
{tcpsocket->write(ui->send_line->text().toLocal8Bit().data());
}