QtDemo-基于TCP的客户端和服务器通信

一个服务器可对多个客户端

直接看效果图:
在这里插入图片描述
下面粘贴部分源码:

MyClient::MyClient(const int clinum,const QString ip,const QString port):
    ui(new Ui::MyClient),m_ip(ip),m_port(port),m_clinum(clinum)
{
    ui->setupUi(this);
    setWindowTitle(QString("客户端")+QString::number(clinum));
    ui->lineEditIp->setText(m_ip);
    ui->lineEditPort->setText(m_port);

    tcpSocket=new QTcpSocket(this);
    connect(tcpSocket,&QTcpSocket::connected,[=](){
        ui->textEditRead->setText(QString("客户端%1:连接服务器成功!").arg(clinum));
    });

    connect(tcpSocket,&QTcpSocket::readyRead,[=]{
        QByteArray arr = tcpSocket->readAll();
        ui->textEditRead->append(arr);
    });

    connect(tcpSocket,&QTcpSocket::disconnected,[=](){
        on_buttonClose_clicked();
    });
}
MyClient::~MyClient()
{
    delete ui;
}

void MyClient::on_buttonConnect_clicked()
{
    qint16 port=m_port.toInt();

    if(tcpSocket->isOpen())
        return;
    tcpSocket->connectToHost(QHostAddress(m_ip),port);

}

void MyClient::on_buttonClose_clicked()
{


    if(!tcpSocket->isOpen())
    {
        return;
    }

    tcpSocket->disconnectFromHost();
    tcpSocket->close();

}

void MyClient::on_buttonSend_clicked()
{

    if(!tcpSocket->isOpen())
        return;
    QString str=QString("客户端%1:").arg(m_clinum)+ui->textEditWrite->toPlainText();
    tcpSocket->write(str.toUtf8().data());
    ui->textEditRead->append(str);
    ui->textEditWrite->clear();
}

MyServer::MyServer(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::MyServer)
{
    ui->setupUi(this);
    setWindowTitle("服务器:8888");

    tcpServer=new QTcpServer(this);
    tcpServer->listen(QHostAddress::Any,8888);

    connect(tcpServer,&QTcpServer::newConnection,[=](){
        if(m_N>1)m_N=0;
        int i=m_N++;
        tcpSocketArr[i]=tcpServer->nextPendingConnection();

        QString ip=tcpSocketArr[i]->peerAddress().toString();
        qint16 port = tcpSocketArr[i]->peerPort();
        QString str=QString("客户端[%1:%2]:连接成功").arg(ip).arg(port);
        ui->textEditRead->append(str);
        connect(tcpSocketArr[i],&QTcpSocket::readyRead,[=](){
            temparr = tcpSocketArr[i]->readAll();
            ui->textEditRead->append(temparr);
            moveInfo(i);
        });

        connect(tcpSocketArr[i],&QTcpSocket::disconnected,[=](){

            tcpSocketArr[i]->disconnectFromHost();
            tcpSocketArr[i]->close();
            tcpSocketArr[i]->deleteLater();
            tcpSocketArr[i]=NULL;
            m_N=i;
        });

    });
}

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


void MyServer::on_buttonClose_clicked()
{

    for(int i=0;i<2;i++)
    {
        if(tcpSocketArr[i]!=NULL&&tcpSocketArr[i]->isOpen())
        {
            tcpSocketArr[i]->disconnectFromHost();

        }
    }

}
void MyServer::moveInfo(int num)
{

    //注意此处的范围,要遍历到每一个客户端
    for(int i=0;i<2;i++)
    {
        if(tcpSocketArr[i]!=NULL&&tcpSocketArr[i]->isOpen()&&(i!=num))
        {

            tcpSocketArr[i]->write(temparr);
        }

    }

}

若原理不太理解可以参考:基于Qt的Tcp简单通信示意图及代码实现思路大同小异

完整代码请点击
(仓库中也有一些其它小项目或Demo需要的自提,如果觉得对您有帮助的话可以star一下哟)

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
QT TCP客户服务器通信的步骤如下: 1. 创建QT TCP客户对象 使用QT提供的QTcpSocket类创建TCP客户对象。可以使用new运算符在堆上动态分配内存,也可以在栈上创建对象。 ``` QTcpSocket *client = new QTcpSocket(this); // 动态分配内存 ``` 2. 连接服务器 使用client对象的connectToHost()函数连接服务器。该函数需要传递服务器的IP地址和口号。 ``` client->connectToHost("127.0.0.1", 8888); // 连接服务器 ``` 3. 发送数据 使用client对象的write()函数发送数据。该函数需要传递待发送的数据和数据长度。 ``` QByteArray data = "Hello World!"; client->write(data, data.length()); // 发送数据 ``` 4. 接收数据 使用client对象的readyRead()信号接收服务器发送的数据。可以使用client对象的read()函数读取接收到的数据。 ``` connect(client, SIGNAL(readyRead()), this, SLOT(readData())); ``` ``` void readData() { QByteArray data = client->readAll(); // 读取数据 qDebug() << data; } ``` 5. 断开连接 使用client对象的disconnectFromHost()函数断开与服务器的连接。 ``` client->disconnectFromHost(); // 断开连接 ``` 完整的QT TCP客户代码如下: ``` #include <QTcpSocket> class Client : public QObject { Q_OBJECT public: Client(QObject *parent = nullptr); ~Client(); private slots: void readData(); private: QTcpSocket *client; }; Client::Client(QObject *parent) : QObject(parent) { client = new QTcpSocket(this); client->connectToHost("127.0.0.1", 8888); connect(client, SIGNAL(readyRead()), this, SLOT(readData())); } Client::~Client() { client->disconnectFromHost(); } void Client::readData() { QByteArray data = client->readAll(); qDebug() << data; } ``` 注意:QTcpSocket是异步的,因此需要使用信号和槽机制来处理数据接收。同时,需要在客户对象的析构函数中调用disconnectFromHost()函数断开与服务器的连接。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值