Qt服务器接受多个客户端

该代码示例展示了如何使用QTcpServer监听套接字并处理新连接,以及如何通过QTcpSocket与多个已连接的客户端进行数据交换。当有新连接时,程序会获取客户端的IP和端口信息,并在文本浏览器中显示。同时,程序能向所有已连接的客户端发送数据。

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

1、指定父对象,监听套接字

  indexSocket = 0;
    //监听套接字,指定父对象,让其自动回收空间
    tcpServer = new QTcpServer(this);
    const QString IP = "192.168.9.11";
    QHostAddress address;
    address.setAddress(IP);
    tcpServer->listen(address, 8888);

    connect(tcpServer, &QTcpServer::newConnection,this,&MainWindow::onNewConnect);

void MainWindow::onNewConnect()
{
    tcpSocket[indexSocket] = tcpServer->nextPendingConnection();//获取连接上得套接字对象
     //获取对方的IP和端口
    QString ip = tcpSocket[indexSocket]->peerAddress().toString();
    qint16 port = tcpSocket[indexSocket]->peerPort();

    QString temp = QString("[%1:%2]:成功连接").arg(ip).arg(port);
    ui->textBrowser->append(temp);

    //必须放在里面,因为建立好链接才能读,或者说tcpSocket有指向才能操作
    for(int i=0; i<indexSocket+1; i++){
        connect(tcpSocket[i], &QTcpSocket::readyRead,
         [=]()
         {
          //从通信套接字中取出内容
             QByteArray array = tcpSocket[i]->readAll();
             if(array.length())
                 ui->textBrowser->append(array);
         }
         );
    }

    indexSocket++;
}

2、给多个客户端发送数据

for(int i=0; i<indexSocket; i++){
          if(NULL == tcpSocket[i]){
                 return;
          }
          //获取编辑区内容
          QString str = ui->textEditSend->toPlainText();
          //给对方发送数据, 使用套接字是tcpSocket
          tcpSocket[i]->write( str.toUtf8().data() );
      }

源文件

.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QDebug>
#include <QTcpServer> //监听套接字
#include <QTcpSocket> //通信套接字//对方的(客户端的)套接字(通信套接字)

#define MAXCONNECT 100

QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE

class MainWindow : public QMainWindow
{
    Q_OBJECT

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

private slots:
    void on_pushButtonClose_clicked();

    void on_pushButtonBreak_clicked();

    void onNewConnect(void);
    void on_pushButtonSend_clicked();

private:
    Ui::MainWindow *ui;
    QTcpServer *tcpServer;
    QTcpSocket  *tcpSocket[MAXCONNECT];
    int indexSocket;
};
#endif // MAINWINDOW_H

.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    indexSocket = 0;
    //监听套接字,指定父对象,让其自动回收空间
    tcpServer = new QTcpServer(this);
    const QString IP = "192.168.9.11";
    QHostAddress address;
    address.setAddress(IP);
    tcpServer->listen(address, 8888);

    connect(tcpServer, &QTcpServer::newConnection,this,&MainWindow::onNewConnect);

}

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

void MainWindow::on_pushButtonClose_clicked()
{
    ui->textBrowser->clear();
    ui->textEditSend->clear();
}

void MainWindow::on_pushButtonBreak_clicked()
{
    for(int i=0; i<indexSocket; i++){
        if(NULL == tcpSocket[i])
        {
            return;
        }
        //主动和客户端端口连接
        tcpSocket[i]->disconnectFromHost();
        tcpSocket[i]->close();
        tcpSocket[i] = NULL;
    }
}

void MainWindow::onNewConnect()
{
    tcpSocket[indexSocket] = tcpServer->nextPendingConnection();//获取连接上得套接字对象
     //获取对方的IP和端口
    QString ip = tcpSocket[indexSocket]->peerAddress().toString();
    qint16 port = tcpSocket[indexSocket]->peerPort();

    QString temp = QString("[%1:%2]:成功连接").arg(ip).arg(port);
    ui->textBrowser->append(temp);

    //必须放在里面,因为建立好链接才能读,或者说tcpSocket有指向才能操作
    for(int i=0; i<indexSocket+1; i++){
        connect(tcpSocket[i], &QTcpSocket::readyRead,
         [=]()
         {
          //从通信套接字中取出内容
             QByteArray array = tcpSocket[i]->readAll();
             if(array.length())
                 ui->textBrowser->append(array);
         }
         );
    }

    indexSocket++;
}

void MainWindow::on_pushButtonSend_clicked()
{
      for(int i=0; i<indexSocket; i++){
          if(NULL == tcpSocket[i]){
                 return;
          }
          //获取编辑区内容
          QString str = ui->textEditSend->toPlainText();
          //给对方发送数据, 使用套接字是tcpSocket
          tcpSocket[i]->write( str.toUtf8().data() );
      }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

weixin_44585751

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值