QTcpServer简单的TCP服务器连接

1、简介

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

声明源文件

cpp 复制代码
#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();
}

声明的头文件

cpp 复制代码
#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QPushButton>
#include <QTextBrowser>
#include <QTcpServer>
#include <QTcpSocket>
#include <QHostAddress>
#include <QMessageBox>
#include <QDebug>

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
相关推荐
cefler2 分钟前
【QT】QSS基础
开发语言·qt
忒可君3 分钟前
Qt/C++开发经验
数据库·c++·qt·学习·c#
forestqq1 小时前
配置docker的proxy指向
运维·服务器·容器
䛩x1 小时前
贪吃蛇小游戏(Qt)
c语言·开发语言·qt·程序人生·游戏程序·命令模式
wanhengwangluo1 小时前
高防服务器如何抵御网络攻击?
服务器·网络攻击·高防服务器
You can do more1 小时前
Qt-qmake语言
开发语言·qt
爱吃番茄炒蛋..2 小时前
Visual Studio 2022 - QT 环境中文字符乱码问题
开发语言·qt·visual studio
贩卖纯净水.2 小时前
虎先锋,你也喜欢线程控制嘛
linux·运维·服务器
桃花源小王子2 小时前
【ansible】role流程实验
linux·运维·服务器
Dylanioucn2 小时前
【网络基础知识】详解TCP/IP协议栈
网络·网络协议·tcp/ip