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
相关推荐
程序猿阿伟21 分钟前
《进程隔离机制:C++多进程编程安全的坚固堡垒》
服务器·c++·安全
----云烟----25 分钟前
Qt获取文件夹下的文件个数(过滤和不过滤的区别)
数据库·qt
Dotrust东信创智25 分钟前
浅谈丨功能安全测试,汽车的守护者
运维·服务器·数据库
cuijian2B27 分钟前
Qt:信号槽
qt
HPC_fac130520678162 小时前
科研深度学习:如何精选GPU以优化服务器性能
服务器·人工智能·深度学习·神经网络·机器学习·数据挖掘·gpu算力
Estar.Lee7 小时前
查手机号归属地免费API接口教程
android·网络·后端·网络协议·tcp/ip·oneapi
傻啦嘿哟8 小时前
代理IP在后端开发中的应用与后端工程师的角色
网络·网络协议·tcp/ip
sun0077008 小时前
ubuntu dpkg 删除安装包
运维·服务器·ubuntu
oi778 小时前
使用itextpdf进行pdf模版填充中文文本时部分字不显示问题
java·服务器