1.IDE:QTCreator
2.实验:编写一个tcp服务端
QTcpsever
QTcpsocket
3.记录:
(1)先搭建界面
(2)服务端代码
a. pro
QT += core gui networkgreaterThan(QT_MAJOR_VERSION, 4): QT += widgetsCONFIG += c++17# You can make your code fail to compile if it uses deprecated APIs.
# In order to do so, uncomment the following line.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0SOURCES += \main.cpp \widget.cppHEADERS += \widget.hFORMS += \widget.ui# Default rules for deployment.
qnx: target.path = /tmp/$${TARGET}/bin
else: unix:!android: target.path = /opt/$${TARGET}/bin
!isEmpty(target.path): INSTALLS += target
b. widget.h
#ifndef WIDGET_H
#define WIDGET_H#include <QWidget>
#include <QTcpServer> //加入头文件
#include <QTcpSocket>
QT_BEGIN_NAMESPACE
namespace Ui {
class Widget;
}
QT_END_NAMESPACEclass Widget : public QWidget
{Q_OBJECTpublic:Widget(QWidget *parent = nullptr);~Widget();QTcpServer *tcpsever; //定义两个指针对象QTcpSocket *tcpsocket;
private slots:void on_openserver_pb_clicked();void new_conneciton_slot(); //server新的连接处理关联函数void readyRead_slot(); //socket准备读关联函数void on_closeserver_pb_clicked();void on_send_pb_clicked();private:Ui::Widget *ui;
};
#endif // WIDGET_H
c. widget.cpp
#include "widget.h"
#include "ui_widget.h"Widget::Widget(QWidget *parent): QWidget(parent), ui(new Ui::Widget)
{ui->setupUi(this);tcpsever = new QTcpServer(this); //指针赋值tcpsocket = new QTcpSocket(this);connect(tcpsever,SIGNAL(newConnection()),this,SLOT(new_conneciton_slot())); //新的连接函数关联
}Widget::~Widget()
{delete ui;
}void Widget::new_conneciton_slot() //新的连接处理函数
{tcpsocket=tcpsever->nextPendingConnection();connect(tcpsocket,SIGNAL(readyRead()),this,SLOT(readyRead_slot())); //关联socket准备读函数
}
void Widget::readyRead_slot() //socket准备读关联函数
{QString receive_buff; //定义一个接受数组receive_buff=tcpsocket->readAll(); //读取所有接受的内容ui->receive_line->appendPlainText(receive_buff); //在接收区显示接收到的内容
}void Widget::on_openserver_pb_clicked() //打开服务器按钮按下处理函数
{tcpsever->listen(QHostAddress::Any,ui->com_number->text().toUInt()); //监听主机上的所有端口,将端口号转为无符号整型
}void Widget::on_closeserver_pb_clicked() //关闭服务器按钮按下处理函数
{tcpsever->close();
}void Widget::on_send_pb_clicked() //当发送按钮按下时处理函数
{tcpsocket->write(ui->send_line->text().toLocal8Bit().data());
}