国庆第五天

widget.h

#ifndef WIDGET_H
#define WIDGET_H

#include 
#include 
#include 
#include 
#include 
#include 

QT_BEGIN_NAMESPACE
namespace Ui { class Widget; }
QT_END_NAMESPACE

class Widget : public QWidget
{
    Q_OBJECT

public:
    Widget(QWidget *parent = nullptr);
    ~Widget();


private slots:
    void on_btn_clicked();
    void newConnection_slot();
    void readyRead_slot();

private:
    Ui::Widget *ui;

    QTcpServer *server;

    QList clientList;
};
#endif // WIDGET_H

main.cpp

#include "widget.h"

#include 

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    Widget w;
    w.show();
    return a.exec();
}

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);
    connect(server,&QTcpServer::newConnection,this,&Widget::newConnection_slot);
}

Widget::~Widget()
{
    delete ui;
}

void Widget::on_btn_clicked()
{
    quint16 port = ui->lineEdit->text().toUInt();

    if(!ui->lineEdit->text().isEmpty() && !server->listen(QHostAddress::Any,port))
    {
        QMessageBox::information(this,"失败","监听失败");
        return ;
    }
    else
    {
        QMessageBox::information(this,"成功","监听成功");
    }
}

void Widget::newConnection_slot()
{
    QTcpSocket *s = server->nextPendingConnection();
    clientList.push_back(s);
    connect(s,&QTcpSocket::readyRead,this,&Widget::readyRead_slot);

}

void Widget::readyRead_slot()
{
    for(int i = 0; i < clientList.size(); i++)
    {
        if(clientList[i]->state() == 0)
        {
            clientList.removeAt(i);
        }
    }

    for(int i = 0; i < clientList.size(); i++)
    {
        if(clientList[i]->bytesAvailable() != 0)
        {
            QByteArray msg = clientList[i]->readAll();
            ui->listWidget->addItem(QString::fromLocal8Bit(msg));
            for(int j = 0; j < clientList.size(); j++)
            {
                clientList[j]->write(msg);
            }
        }
    }
}


你可能感兴趣的:(数据库)