#include "widget.h"
#include "ui_widget.h"
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
, server(new QTcpServer)
{
ui->setupUi(this);
}
Widget::~Widget()
{
delete ui;
}
void Widget::on_pushButton_clicked()
{
quint16 port=ui->lineEdit->text().toUInt();
if(server->listen(QHostAddress::Any,port))
{
QMessageBox::information(this,"","服务器打开成功");
}
else
{
QMessageBox::information(this,"","服务器打开失败");
return;
}
connect(server,&QTcpServer::newConnection,this,&Widget::connect_slot);
}
void Widget::connect_slot()
{
QTcpSocket *s=server->nextPendingConnection();
socketList.push_back(s);
connect(s,&QTcpSocket::readyRead,this,&Widget::ready_slot);
}
void Widget::ready_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(i)->write(msg);
}
}
}
}
6.19作业
最新推荐文章于 2024-08-17 23:59:05 发布