1.QT基于TCP服务器端
头文件
#ifndef WIDGET_H
#define WIDGET_H#include <QWidget>
#include <QTcpServer> //服务器类
#include <QMessageBox> //消息对话框类
#include <QTcpSocket> //客户端类
#include <QList> //链表容器类namespace Ui {
class Widget;
}class Widget : public QWidget
{Q_OBJECTpublic:explicit Widget(QWidget *parent = nullptr);~Widget();private slots:void on_startBtn_clicked();public slots:void newConnection_slot(); //newConnection信号对应的槽函数声明void readyRead_slot(); //readyRead()信号对应的槽函数声明
private:Ui::Widget *ui;//实例化一个服务端对象QTcpServer *server;//实例化存放套接字链表容器QList<QTcpSocket *> list;
};#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);}Widget::~Widget()
{delete ui;
}//启动服务器对应的槽函数处理
void Widget::on_startBtn_clicked()
{//获取端口号quint16 port = ui->portedit->text().toUInt();//设置监听状态if(server->listen(QHostAddress::Any,port)){//监听成功QMessageBox::information(this,"","监听成功!");}else {//监听失败QMessageBox::information(this,"","监听失败!");return;}//当执行程序到这一步,说明监听成功,可以接收客户端连接请求,把信号进行连接connect(server,&QTcpServer::newConnection,this,&Widget::newConnection_slot);
}//newConnection信号对应的槽函数实现
void Widget::newConnection_slot()
{//获取客户端套接字QTcpSocket *s = server->nextPendingConnection();//将套接字存入容器list.push_back(s);//当客户发来信息会发送readyRead()信号,连接到自定义槽函数中connect(s,&QTcpSocket::readyRead,this,&Widget::readyRead_slot);
}//readyRead()信号对应的槽函数实现
void Widget::readyRead_slot()
{//移除已退出客户端for(int i=0; i<list.count();i++){if(list.at(i)->state() == 0){//移除未连接客户端list.removeAt(i);}}//获取客户端发送信息,并广播for(int i=0; i<list.count();i++){if(list.at(i)->bytesAvailable() >0){QByteArray msg = list.at(i)->readAll();//写到窗口中ui->msgWidget->addItem(QString::fromLocal8Bit(msg));//广播for(int j=0;j<list.count();j++){list.at(j)->write(msg);}}}
}
效果图
2.思维导图