widget.h
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QTcpServer>
#include <QMessageBox>
#include <QList>
#include <QTcpSocket>
namespace Ui {
class Widget;
}
class Widget : public QWidget
{
Q_OBJECT
public:
explicit Widget(QWidget *parent = nullptr);
~Widget();
private slots:
void on_startBtn_clicked();
public slots:
void newConnection_slot();
void readyRead_slot();
private:
Ui::Widget *ui;
QTcpServer *server;
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)
{
ui->setupUi(this);
server = new QTcpServer(this);
}
Widget::~Widget()
{
delete ui;
}
void Widget::on_startBtn_clicked()
{
qint16 port=ui->portEdit->text().toUInt();
if(server->listen(QHostAddress::Any,port))
{
QMessageBox::information(this,"提示","服务器启动成功");
}else
{
QMessageBox::information(this,"提示","服务器启动失败");
}
connect(server,&QTcpServer::newConnection,this,&Widget::newConnection_slot);
}
void Widget::newConnection_slot()
{
QTcpSocket *s=server->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->msgWidget->addItem(QString::fromLocal8Bit(msg));
for(int j=0;j<socketList.count();j++)
{
socketList[i]->write(msg);
}
}
}
}