QTは単純なTCPサーバーとクライアントを実装します

TCP実装には、サーバーとクライアントが含まれます。サーバーには、リスニングソケットと通信ソケットの2つのソケットがあります。クライアントには、通信ソケットが1つだけあります。
サーバーは次のように実装されます
。serverwidget.h

#ifndef SERVERWIDGET_H
#define SERVERWIDGET_H
#include <QWidget>
#include<QTcpServer>//监听套接字
#include<QTcpSocket>//通信套接字
#ifdef WIN32
#pragma execution_character_set("utf-8")
#endif
namespace Ui {
    
    
class ServerWidget;
}
class ServerWidget : public QWidget
{
    
    
    Q_OBJECT
public:
    explicit ServerWidget(QWidget *parent = nullptr);
    ~ServerWidget();
private slots:
    void on_buttonClose_clicked();
    void on_buttonSend_clicked();
private:
    Ui::ServerWidget *ui;
    QTcpServer *tcpServer;//监听套接字
    QTcpSocket *tcpSocket;//通信套接字
};
#endif // SERVERWIDGET_H

serverwidget.cpp

#include "serverwidget.h"
#include "ui_serverwidget.h"
ServerWidget::ServerWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::ServerWidget)
{
    
    
    ui->setupUi(this);
    setWindowTitle("服务器");
    tcpServer = NULL;
    tcpSocket = NULL;
    //监听套接字,指定父对象,让其自动回收空间
    tcpServer = new QTcpServer(this);
    //绑定和监听
    tcpServer->listen(QHostAddress::Any,8888);

    connect(tcpServer,&QTcpServer::newConnection,
                [=]()
                    {
    
    
                        //取出建立好连接的套接字
                        tcpSocket = tcpServer->nextPendingConnection();
                        //获取对方的IP和端口
                        QString ip = tcpSocket->peerAddress().toString();
                        qint16 port = tcpSocket->peerPort();
                        QString temp = QString("[%1:%2]:成功连接").arg(ip).arg(port);

                        ui->textEditRead->setText(temp);

                        connect(tcpSocket,&QTcpSocket::readyRead,
                                [=]()
                                    {
    
    
                                        //从通信套接字中取出内容
                                        QByteArray array = tcpSocket->readAll();
                                        ui->textEditRead->append(array);
                                    }
                                );
                    }
            );
}
ServerWidget::~ServerWidget()
{
    
    
    delete ui;
}
//断开连接
void ServerWidget::on_buttonClose_clicked()
{
    
    
    if(NULL == tcpSocket)
    {
    
    
        return;
    }
    //主动和客户端断开连接
    tcpSocket->disconnectFromHost();
    tcpSocket->close();
    tcpSocket = NULL;
}
//发送数据
void ServerWidget::on_buttonSend_clicked()
{
    
    
    if(NULL == tcpSocket)
    {
    
    
        return;
    }
    //获取编辑区内容
    QString str = ui->textEditWrite->toPlainText();
    //给对方发送数据,使用套接字tcpSocket
    tcpSocket->write(str.toUtf8().data());
}

クライアント:
clientwidget.h

#ifndef CLIENTWIDGET_H
#define CLIENTWIDGET_H
#include <QWidget>
#ifdef WIN32
#pragma execution_character_set("utf-8")
#endif
#include<QTcpSocket>//通信套接字
namespace Ui {
    
    
class ClientWidget;
}
class ClientWidget : public QWidget
{
    
    
    Q_OBJECT
public:
    explicit ClientWidget(QWidget *parent = nullptr);
    ~ClientWidget();
private slots:
    void on_buttonConnect_clicked();
    void on_buttonSend_clicked();
    void on_buttonClose_clicked();
private:
    Ui::ClientWidget *ui;
    QTcpSocket *tcpSocket;//通信套接字
};
#endif // CLIENTWIDGET_H

clientwidget.cpp

#include "clientwidget.h"
#include "ui_clientwidget.h"
#include<QHostAddress>
ClientWidget::ClientWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::ClientWidget)
{
    
    
    ui->setupUi(this);
    setWindowTitle("客户端");
    tcpSocket = NULL;
    //动态分配空间,指定父对象
    tcpSocket = new QTcpSocket(this);
    //只要成功和对方建立好连接,通信套接字会自动触发connected(),如果对方主动断开连接,通信套接字会自动触发disconnect()
    connect(tcpSocket,&QTcpSocket::connected,
            [=]()
                {
    
    
                    ui->textEditRead->setText("成功和服务器建立连接");
                }
            );
    connect(tcpSocket,&QTcpSocket::readyRead,
            [=]()
                {
    
    
                    //获取对方发送的内容
                    QByteArray array = tcpSocket->readAll();
                    //追加到编辑区
                    ui->textEditRead->append(array);
                }
            );
}
ClientWidget::~ClientWidget()
{
    
    
    delete ui;
}
void ClientWidget::on_buttonConnect_clicked()
{
    
    
    //获取服务器IP和端口
    QString ip = ui->lineEditIp->text();
    qint16 port = ui->lineEditPort->text().toInt();
    //主动和服务器建立连接
    tcpSocket->connectToHost(QHostAddress(ip),port);
}
void ClientWidget::on_buttonSend_clicked()
{
    
    
    //获取编辑框内容
    QString str = ui->textEditWrite->toPlainText();
    //发送数据
    tcpSocket->write(str.toUtf8().data());
}
void ClientWidget::on_buttonClose_clicked()
{
    
    
    //主动和对方断开连接
    tcpSocket->disconnectFromHost();
    tcpSocket->close();
}

おすすめ

転載: blog.csdn.net/weixin_40355471/article/details/110391163