QTcpSocket - Server

本文档详细介绍了如何使用QTcpSocket构建一个服务器,提供了源码链接,帮助读者理解QTcpSocket在服务器端的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include "mainwindow.h"
#include "ui_serverWindow.h"

#include <QNetworkInterface>
#include <QDateTime>

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

    init();
    initConnect();
}

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

void MainWindow::slotNewConnection()
{
    mCurClient = mTcpServer->nextPendingConnection();
    mTcpClientList.append(mCurClient);
    ui->mComboBox->addItem(tr("%1:%2")
                           .arg(mCurClient->peerAddress().toString().split("::ffff:")[1])
            .arg(mCurClient->peerPort()));
    connect(mCurClient, &QTcpSocket::readyRead, this, &MainWindow::slotReadData);
    connect(mCurClient, &QTcpSocket::disconnected, this, &MainWindow::slotDisconnected);
}

void MainWindow::slotConnectNetwork()
{
    if(mSwitch)
    {
        disConnect();
        mSwitch = false;
    }
    else
    {
        connet();
        mSwitch = true;
    }

}

void MainWindow::slotSendText()
{
    QString data = ui->mSendTextEdit->toPlainText();
    if(ui->mComboBox->currentText() == QStringLiteral("全部链接"))
    {
        for(auto client : mTcpClientList)
        {
            if(data.simplified().size())
            {
                client->write(data.toUtf8());
            }
        }
    }
    else
    {
        //指定连接
        QString clientIP = ui->mComboBox->currentText().split(":")[0];
        int clientPort = ui->mComboBox->currentText().split(":")[1].toInt();
        for(auto client : mTcpClientList)
        {
            if(client->peerAddress().toString().split("::ffff:")[1] == clientIP && client->peerPort() == clientPort)
            {
                client->write(data.toUtf8());
                return; //ip:port唯一,无需继续检索
            }
        }
    }

    ui->mSendTextEdit->clear();
}

void MainWindow::slotReadData()
{
    QTcpSocket* socket = static_cast<QTcpSocket*>(sender());
    QByteArray buffer = socket->readAll();
    QString ipAndPort;

    ipAndPort = tr("[%1:%2]:")
            .arg(socket->peerAddress().toString().split("::ffff:")[1])
            .arg(socket->peerPort());

    ui->mReceiveEdit->append(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"));
    ui->mReceiveEdit->append(ipAndPort);
    ui->mReceiveEdit->append(QString::fromUtf8(buffer));
}

void MainWindow::slotDisconnected()
{
    QTcpSocket* socket = static_cast<QTcpSocket*>(sender());

    if(socket->state() == QAbstractSocket::UnconnectedState)
    {
        // 删除存储在combox中的客户端信息
        ui->mComboBox->removeItem(
                    ui->mComboBox->findText(tr("%1:%2")
                                            .arg(socket->peerAddress().toString().split("::ffff:")[1])
                    .arg(socket->peerPort())));
        // 删除存储在tcpClient列表中的客户端信息
        socket->destroyed();
        mTcpClientList.removeOne(socket);
    }
}

void MainWindow::init()
{
    setWindowTitle(QStringLiteral("Server"));
    mTcpServer = new QTcpServer(this);
    ui->mAddrEdit->setText(QNetworkInterface().allAddresses().at(1).toString());   //获取本地IP
    ui->mSendButton->setEnabled(false);
    setLocalHostIp();
}

void MainWindow::initConnect()
{
    connect(mTcpServer, &QTcpServer::newConnection, this, &MainWindow::slotNewConnection);

    connect(ui->mConnectButton,&QPushButton::clicked,this,&MainWindow::slotConnectNetwork);
    connect(ui->mClearButton,&QPushButton::clicked,this,[this](){ui->mReceiveEdit->clear();});
    connect(ui->mSendButton,&QPushButton::clicked,this,&MainWindow::slotSendText);
}

void MainWindow::setLocalHostIp()
{
    for(auto address : QNetworkInterface().allAddresses())
    {
        ui->mReceiveEdit->append(address.toString());
    }
}

void MainWindow::connet()
{
    bool ok = mTcpServer->listen(QHostAddress::Any, static_cast<quint16>(ui->mPortEdit->text().toInt()));
    if(ok)
    {
        ui->mConnectButton->setText(QStringLiteral("断开"));
        ui->mSendButton->setEnabled(true);
    }
}

void MainWindow::disConnect()
{
    for(int i=0; i<mTcpClientList.length(); i++)//断开所有连接
    {
        mTcpClientList[i]->disconnectFromHost();
        bool ok = mTcpClientList[i]->waitForDisconnected(1000);
        if(!ok)
        {
            // 处理异常
        }
        mTcpClientList.removeAt(i);  //从保存的客户端列表中取去除
    }
    mTcpServer ->close();     //不再监听端口

    ui->mConnectButton->setText(QStringLiteral("连接"));
    ui->mSendButton->setEnabled(false);
}

在这里插入图片描述

源码链接 Server

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值