通信服务端实现
widget.h文件
#ifndef WIDGET_H
#define WIDGET_H#include <QWidget>
#include <QTcpServer>//服务器类
#include <QMessageBox>//消息
#include <QTcpServer>
#include <QList>
#include <QTcpSocket>QT_BEGIN_NAMESPACE
namespace Ui { class Widget; }
QT_END_NAMESPACEclass Widget : public QWidget
{
Q_OBJECTpublic:
Widget(QWidget *parent = nullptr);
~Widget();private slots:
void on_pushButton_2_clicked();public slots:
void newConnection_slot();//newConnection槽函数的声明
void readyRead_slot();private:
Ui::Widget *ui;
QTcpServer *serve;
QList<QTcpSocket *> socketList;
};
#endif // WIDGET_H
widget.cpp 文件
#include "widget.h"
#include "ui_widget.h"Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
,serve(new QTcpServer(this))//服务器指针实例空间
{
ui->setupUi(this);
}Widget::~Widget()
{
delete ui;
}
//服务器对用槽函数
void Widget::on_pushButton_2_clicked()
{
//获取ui界面上的端口号
quint16 port = ui->lineEdit->text().toUInt();//将字符串转化成整形
//监听
//函数原型 bool listen(const QHostAddress &address = QHostAddress::Any, quint16 port = 0);
//参数:监听的主机 监听的端口号
if(serve->listen(QHostAddress::Any,port))//成功返回ture失败返回false
{
QMessageBox::information(this,"","启动服务器成功");
}
else
{
QMessageBox::information(this,"","启动服务器失败");
return;
}
connect(serve,&QTcpServer::newConnection,this,&Widget::newConnection_slot);
}void Widget::newConnection_slot()
{
QTcpSocket *s = serve->nextPendingConnection();
socketList.push_back(s);
connect(s,&QTcpSocket::readyRead,this,&Widget::readyRead_slot);}
void Widget::readyRead_slot()
{
//遍历客户端容器,移除无效客户端
for(int i=0;i<socketList.count();i++)
// 容器元素个数
{
//移除无效客户端
if(socketList.at(i)->state() == 0){
//删除该元素
socketList.removeAt(i);
}
}
//遍历客户端容器寻找哪个客户端有数据待读
for(int i=0;i<socketList.count();i++){
//函数功能数据的字节大小
if(socketList.at(i)->bytesAvailable() != 0){//说明有数据
//读取数据
QByteArray msg = socketList.at(i)->readAll();
//将读取到的数据放入ui界面上
ui->ss->addItem(QString::fromLocal8Bit(msg));
//将数据广播给所有客户端
for(int j=0;j<socketList.count();j++){
socketList.at(j)->write(msg);
}
}
}
}