chat_QT服务器端:
//.h
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include<QTcpServer> //服务器类
#include<QTcpSocket> //客户端类
#include<QMessageBox> //对话框类
#include<QList> //链表容器
#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_pushButton_clicked();
void newConnection_slot();
void readyRead_muslot();
private:
Ui::Widget *ui;
//定义服务器指针
QTcpServer *server;
//定义客户端容器
QList<QTcpSocket *>socketList;
};
#endif // WIDGET_H
//.cpp
#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_pushButton_clicked()
{
//获取ui界面上的端口号
quint16 port = ui->lineEdit->text().toUInt();
//将服务器设置监听状态
if(server->listen(QHostAddress::Any, port)){
QMessageBox::information(this, "提示", "客户端连接成功");
}else{
QMessageBox::information(this, "提示", "客户端连接失败");
}
//将客户端想要连接时服务器发射的newConnect信号与对应槽函数连接
connect(server, &QTcpServer::newConnection, this, &Widget::newConnection_slot);
}
//处理newCOnnection信号对应的槽函数
void Widget::newConnection_slot(){
//获取最新连接的客户端套接字
QTcpSocket *s = server->nextPendingConnection();
//将套接字放入客户端容器中
socketList.push_back(s);
//将readyRead信号与对应的槽函数连接
connect(s, &QTcpSocket::readyRead, this, &Widget::readyRead_muslot);
}
void Widget::readyRead_muslot(){
//移除无效的客户端
for(int i = 0; i < socketList.count(); i++){
//查看客户端状态
if(socketList.at(i) == 0){
socketList.removeAt(i);
}
}
//遍历客户端套接字,查看那个客户端有数据
for(int i = 0; i < socketList.count(); i++){
//判断套接字中是否有数据
QByteArray msg = socketList.at(i)->readAll();
//将数据显示到ui界面上
ui->listWidget->addItem(QString::fromLocal8Bit(msg));
//将数据发射给所有的客户端套接字中
for(int j = 0; j < socketList.count(); j++){
socketList.at(j)->write(msg);
}
}
}
思维导图: