服务器
头文件:
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include<QTcpServer> //服务器头文件
#include<QTcpSocket> //客户端头文件
#include<QList> //链表容器
#include<QMessageBox> //消息对话框
#include<QDebug>
QT_BEGIN_NAMESPACE
namespace Ui { class Widget; }
QT_END_NAMESPACE
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(QWidget *parent = nullptr);
~Widget();
private slots:
void on_startBtn_clicked();
void newConnection_slot(); //自定义处理newConnection信号的槽函数的声明
void readyRead_slot(); //自定义处理readyRead信号的槽函数的声明
private:
Ui::Widget *ui;
//定义服务器指针
QTcpServer *server;
//定义客户端容器
QList<QTcpSocket *> clientList;
};
#endif // WIDGET_H
源文件:
#include "widget.h"
#include "ui_widget.h"
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
{
ui->setupUi(this);
//实例化一个服务器
server = new QTcpServer(this);
//此时,服务器已经成功进入监听状态,如果有客户端向服务器发来连接请求
//那么该服务器,就会自动发射一个newConnection的信号,我们可以将该信号连接到对应槽函数中执行相关逻辑
//由于只需要连接一次即可,所以可以将该连接放在构造函数中完成
connect(server, &QTcpServer::newConnection, this, &Widget::newConnection_slot);
}
Widget::~Widget()
{
delete ui;
}
//启动服务器按钮对应的槽函数
void Widget::on_startBtn_clicked()
{
quint16 port = ui->portEdit->text().toUInt()