欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

QT TCP 多客户端读写

程序员文章站 2022-03-15 20:34:41
...

直接上代码

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QTcpServer>
#include <QTcpSocket>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = nullptr);
    ~MainWindow();

private slots:
    void on_pushButton_clicked();

private:
    Ui::MainWindow *ui;

    QStringList list;
    QList<QTcpSocket*> socketList;

    QTcpServer *mytcp = nullptr;
    QTcpSocket *mysock = nullptr;
};

#endif // MAINWINDOW_H

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "QDebug"
#define cout qDebug()  << "[" <<__FILE__ <<":"<<__FUNCTION__<<":"<<__LINE__ <<"]"


MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    mytcp = new QTcpServer;
    mysock = new QTcpSocket;
    cout << "listen";
    //关联客户端连接信号newConnection
    connect(mytcp,&QTcpServer::newConnection,this,
            [=]()mutable
    {
        cout << "new connected";
        mysock = mytcp->nextPendingConnection();    //获取套接字
        socketList.append(mysock);  //记录连接的socket
        cout << socketList;
        QString info = QString("%1:%2").arg(mysock->peerAddress().toString()).arg(mysock->peerPort()); //连接的socket的IP,port
        cout << info;
        list << info;
        ui->comboBox->clear();
        ui->comboBox->addItems(list);
        //断开连接
        connect(mysock,&QTcpSocket::disconnected,this,
                [=]()mutable
        {
            QTcpSocket *mysock = (QTcpSocket*)sender();//掉线对象
            QString info = QString("%1:%2").arg(mysock->peerAddress().toString()).arg(mysock->peerPort());
            cout << info;//打印出掉线对象的ip
            socketList.removeOne(mysock);   //移除断开的socket
            list.removeOne(info);
            ui->comboBox->clear();
            ui->comboBox->addItems(list);
        }
        );
        //接收数据
        connect(mysock,&QTcpSocket::readyRead,this,
                [=]()mutable
        {
          QTcpSocket *mysock = (QTcpSocket*)sender();//掉线对象
          QString info = QString("%1:%2").arg(mysock->peerAddress().toString()).arg(mysock->peerPort());
          cout << info;//打印出掉线对象的ip
          ui->textEdit->append(info + "->" + mysock->readAll());
        }
        );
    }
    );
    //启动服务器监听
    mytcp->listen(QHostAddress::Any,8899);

}

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

void MainWindow::on_pushButton_clicked()
{
    QTcpSocket *mysock = socketList.at(ui->comboBox->currentIndex());
    QString info = QString("%1:%2").arg(mysock->peerAddress().toString()).arg(mysock->peerPort());
    cout << info << mysock;
    mysock->write(ui->lineEdit->text().toLatin1(),ui->lineEdit->text().size());
}