QT TCP 멀티 클라이언트 읽기/쓰기

18988 단어 #TCP

직접 부호

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include 
#include 
#include 

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__>


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());
}


좋은 웹페이지 즐겨찾기