思维导图
实现服务器连接多个客户端局域网
#include "widget.h"
#include "ui_widget.h"
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
,sever(new QTcpServer(this))
{
ui->setupUi(this);
}
Widget::~Widget()
{
delete ui;
}
void Widget::on_pushButton_clicked()
{
//quint16 port = ui->lineEdit->text(),toULnt();
quint16 port=ui->lineEdit->text().toUInt();
if(sever->listen(QHostAddress::Any,port))
{
QMessageBox::information(this,"","启动服务状态");
}
else
{
QMessageBox::information(this,"","服务器启动失败");
return;
}
connect(sever,&QTcpServer::newConnection,this,&Widget::newConnection_slot);
}
void Widget::newConnection_slot()
{
QTcpSocket *s = sever->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->listWidget->addItem(QString::fromLocal8Bit(msg));
for(int j=0;j<socketList.count();j++)
{
socketList.at(j)->write(msg);
}
}
}
}