QTcpServer简单的TCP服务器连接

1、简介

简单实现控制TCP服务器获取连接的套接字。点击断开服务器即可关闭所有连接,最大连接数量为5个。

声明源文件

#include "mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
{
    //设置固定大小
    setFixedSize(1024,600);

    btnClearText = new QPushButton(this);
    btnCtrlServer = new QPushButton(this);
    textRecvBrowser = new QTextBrowser(this);

    //按键清空
    btnClearText->setGeometry(48,40,200,60);
    btnClearText->setText("清空浏览");

    //设置控制按钮
    btnCtrlServer->setGeometry(48, 40+40+30 , 200, 60);
    btnCtrlServer->setText("打开服务");

    //浏览处理
    textRecvBrowser->setGeometry(300, 40, 649, 500);

    //连接处理
    QObject::connect(btnClearText, SIGNAL(clicked()), this, SLOT(on_pushButton_textRecvBrowser()));
    QObject::connect(btnCtrlServer, SIGNAL(clicked()),this, SLOT(on_pushButton_ctrlTcpServer()));

    //TCP服务器处理
    tcpServer = new QTcpServer(this);
    QObject::connect(tcpServer, SIGNAL(newConnection()),this, SLOT(on_tcpServer_newConnectCallHandler()));

    //最大连接数量5个
    tcpServer->setMaxPendingConnections(5);
    tcpServer->listen(QHostAddress("127.0.0.1"), 80);
    if(tcpServer->isListening())
        btnCtrlServer->setText("关闭服务");
    else
        btnCtrlServer->setText("打开服务");

}

MainWindow::~MainWindow()
{
    delete btnClearText;
    delete btnCtrlServer;
    delete textRecvBrowser;
    delete tcpServer;
}

//清空浏览记录
void MainWindow::on_pushButton_textRecvBrowser()
{
    textRecvBrowser->clear();
}

//
void MainWindow::on_pushButton_ctrlTcpServer()
{
    //状态查询
    if(tcpServer->isListening())
    {
        //遍历所有数据
        foreach(QTcpSocket* tcpSocket, tcpSocketList)
        {
            if(tcpSocket->state() == QAbstractSocket::ConnectedState)
                tcpSocket->close();//关闭连接
        }

        //
        tcpServer->close();
    }
    else
        tcpServer->listen(QHostAddress::Any, 80);

    //监听状态
    if(tcpServer->isListening())
        btnCtrlServer->setText("关闭服务");
    else
        btnCtrlServer->setText("打开服务");
}

//IPv6转换IPv4
QString convert_to_ipv4_addr(QHostAddress &addr)
{
    quint32  addr_origin = addr.toIPv4Address();
    QHostAddress addr_host = QHostAddress(addr_origin);
    QString  addr_str = addr_host.toString();
    return addr_str;
}

//新建连接
void MainWindow::on_tcpServer_newConnectCallHandler()
{
    while (tcpServer->hasPendingConnections()) {

        //获取连接
        QTcpSocket *tcpSocket = tcpServer->nextPendingConnection();

        //添加指针列表
        tcpSocketList.append(tcpSocket);

        //显示具体连接信息
        QHostAddress ipv6 = tcpSocket->peerAddress();
        textRecvBrowser->append(convert_to_ipv4_addr(ipv6) + ":" + QString::number(tcpSocket->peerPort()));

        //设置连接
        QObject::connect(tcpSocket, SIGNAL(readyRead()),this, SLOT(on_tcpSocket_readyRead()));
        QObject::connect(tcpSocket, SIGNAL(disconnected()), this, SLOT(on_tcpSocket_disconnected()));

        //
        qDebug() << "当前连接数量" << tcpSocketList.size();
    }

}

void MainWindow::on_tcpSocket_disconnected()
{
    QTcpSocket* socket = qobject_cast<QTcpSocket *>(sender()); //当前信息

    //断开所有连接
    if(socket->state() == QAbstractSocket::ConnectedState)
        socket->close();//关闭连接

    //断开连接则清除
    tcpSocketList.removeOne(socket);

    textRecvBrowser->append("已断开连接");

    qDebug() << "当前连接数量" << tcpSocketList.size();
}

//
void MainWindow::on_tcpSocket_readyRead()
{
    QTcpSocket* socket = qobject_cast<QTcpSocket *>(sender());  // 取得当前socket对象

    socket->write("Hello",5);
//    QMessageBox msgBox(this);

//    msgBox.setText("我是准备好读数据");
//    msgBox.setWindowTitle("提示");
//    msgBox.exec();
}

声明的头文件

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

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

class MainWindow : public QMainWindow
{
    Q_OBJECT

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

private slots:
    void on_pushButton_textRecvBrowser();
    void on_pushButton_ctrlTcpServer();
    void on_tcpServer_newConnectCallHandler();


    void on_tcpSocket_readyRead();
    void on_tcpSocket_disconnected();
private:
    QList<QTcpSocket *>  tcpSocketList;

    QPushButton   *btnCtrlServer = nullptr;
    QPushButton   *btnClearText = nullptr;
    QTextBrowser  *textRecvBrowser = nullptr;
    QTcpServer    *tcpServer = nullptr;
};
#endif // MAINWINDOW_H

你可能感兴趣的:(tcp/ip,服务器,qt)