本文主要是介绍6月19日作业,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
思维导图
实现服务器连接多个客户端局域网
#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);}}}
}
这篇关于6月19日作业的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!