当前位置:   article > 正文

QTcpServer,QTcpSocket学习,实现简单的服务器与客户端_qtcpserver与qtcpsocket导入

qtcpserver与qtcpsocket导入

1.实现简单服务器

只需要listen,并且connect QTcpServer::newConnection即可,m_tcpSocket = m_server->nextPendingConnection();获取已连接的套接字,connect QTcpSocket::readyRead即可读取传来的数据。
客户端发来的消息会被显示。

#ifndef SIMPLEQTCPSERVER_H
#define SIMPLEQTCPSERVER_H

#include <QObject>
#include <QWidget>

class QTcpServer;
class QTextEdit;
class QTcpSocket;

class SimpleQTcpServer : public QWidget
{
    Q_OBJECT
public:
    explicit SimpleQTcpServer(QWidget *parent = nullptr);

public slots:
    void showMes(QString mes);

    void newConnectionProcess();

signals:

private:
    QTcpServer *m_server;
    QTcpSocket *m_tcpSocket;
    QTextEdit *showMesWindow;

};

#endif // SIMPLEQTCPSERVER_H

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
#include "simpleqtcpserver.h"

#include <QTcpServer>
#include <QTextEdit>
#include <QHostAddress>
#include <QTcpSocket>
#include <QVBoxLayout>

SimpleQTcpServer::SimpleQTcpServer(QWidget *parent) : QWidget(parent)
{
    m_server = new QTcpServer(this);
    m_server->listen(QHostAddress::Any, 9001);

    connect(m_server, &QTcpServer::newConnection, this, &SimpleQTcpServer::newConnectionProcess);


    showMesWindow = new QTextEdit(this);

    QVBoxLayout *layout = new QVBoxLayout(this);
    layout->addWidget(showMesWindow, 1);

}

void SimpleQTcpServer::showMes(QString mes)
{
    showMesWindow->insertPlainText(mes);
    //showMesWindow->insertPlainText("\n");
}

void SimpleQTcpServer::newConnectionProcess()
{
    m_tcpSocket = m_server->nextPendingConnection();
    showMes(QString("新连接客户端ip:%1 port:%2\n")
            .arg(QHostAddress(m_tcpSocket->peerAddress().toIPv4Address()).toString())
            .arg(m_tcpSocket->peerPort()));

    connect(m_tcpSocket, &QTcpSocket::disconnected, this, [=]{
        m_tcpSocket->deleteLater();
        showMes(QString("客户端断开\n"));});

    connect(m_tcpSocket, &QTcpSocket::readyRead, this, [=]{
        while (m_tcpSocket->canReadLine()) {
            showMes(QString("客户端消息:%1").arg(QString(m_tcpSocket->readLine())));
        }
    });

}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48

2.简单客户端

只需要连接,之后connect各种信号即可。

QString result = QString::asprintf("%s", datagram.toHex().toUpper().constData());
  • 1

十六进制数直接转为QString显示,不再具有二进制数意义,仅仅只是字符串。
服务器发来的消息会被显示。

#ifndef SIMPLEQTCPCLIENT_H
#define SIMPLEQTCPCLIENT_H

#include <QWidget>

class QLineEdit;
class QPushButton;
class QHBoxLayout;
class QTcpSocket;
class QVBoxLayout;
class QLabel;
class QTextEdit;

class SimpleQTcpClient : public QWidget
{
    Q_OBJECT
public:
    explicit SimpleQTcpClient(QWidget *parent = nullptr);
    ~SimpleQTcpClient();

    void showMessage(QString message);

signals:

private:
    QLineEdit *sendLineEdit;
    QPushButton *sendBtn;
    QPushButton *connectBtn;
    QPushButton *disconnectBtn;
    QLabel *connectLabel;
    QLineEdit *ipLineEdit;
    QLineEdit *portLineEdit;
    QHBoxLayout *sendLayout;
    QHBoxLayout *connectLayout;
    QVBoxLayout *mainLayout;
    QTcpSocket* client;

    QTextEdit *messageTextEdit;

};

#endif // SIMPLEQTCPCLIENT_H

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
#include "simpleqtcpclient.h"
#include <QLineEdit>
#include <QPushButton>
#include <QHBoxLayout>
#include <QTcpSocket>
#include <QVBoxLayout>
#include <QLabel>
#include <QDebug>
#include <QAbstractSocket>
#include <QTextEdit>
SimpleQTcpClient::SimpleQTcpClient(QWidget *parent) : QWidget(parent)
{
    sendLineEdit = new QLineEdit(this);
    sendBtn = new QPushButton(this);
    sendBtn->setText("发送");
    sendLayout = new QHBoxLayout();
    sendLayout->addWidget(sendLineEdit, 1);
    sendLayout->addWidget(sendBtn, 0);

    connectBtn = new QPushButton(this);
    connectBtn->setText("连接");
    disconnectBtn= new QPushButton(this);
    disconnectBtn->setText("断开连接");
    disconnectBtn->setDisabled(true);
    ipLineEdit = new QLineEdit(this);
    ipLineEdit->setText("192.168.54.41");
    portLineEdit = new QLineEdit(this);
    portLineEdit->setText("8008");
    connectLabel = new QLabel(this);
    connectLabel->setText("未连接");
    connectLayout = new QHBoxLayout();
    connectLayout->addWidget(ipLineEdit, 1);
    connectLayout->addWidget(portLineEdit, 0);
    connectLayout->addWidget(connectBtn, 0);
    connectLayout->addWidget(disconnectBtn, 0);
    connectLayout->addWidget(connectLabel, 0);

    messageTextEdit = new QTextEdit(this);

    mainLayout = new QVBoxLayout(this);
    mainLayout->addLayout(connectLayout);
    mainLayout->addLayout(sendLayout);
    mainLayout->addWidget(messageTextEdit, 1);


    client = new QTcpSocket(this);
    //

    connect(sendBtn, &QPushButton::clicked, this, [=]{
        if(client->isValid()){
            QByteArray str = sendLineEdit->text().toUtf8();
            str.append('\n');
            client->write(str);
        }
    });

    connect(connectBtn, &QPushButton::clicked, this, [=]{
        client->connectToHost(ipLineEdit->text(), portLineEdit->text().toInt());
        connectBtn->setDisabled(true);
        disconnectBtn->setDisabled(false);
        ipLineEdit->setDisabled(true);
        portLineEdit->setDisabled(true);
        connectLabel->setText("连接中");
    });

    connect(disconnectBtn, &QPushButton::clicked, this, [=]{
        client->disconnectFromHost();
        connectBtn->setDisabled(false);
        disconnectBtn->setDisabled(true);
        ipLineEdit->setDisabled(false);
        portLineEdit->setDisabled(false);
        connectLabel->setText("未连接");
    });

    connect(client, &QTcpSocket::connected, this, [=]{
        connectLabel->setText("已连接");
    });

    connect(client, &QTcpSocket::disconnected, this, [=]{
        //client->deleteLater();
        connectLabel->setText("未连接");
    });

    connect(client, &QTcpSocket::readyRead, this, [=]{
        //while (client->canReadLine()) {
            //读数据包
            QByteArray datagram = client->readAll();
            //datagram.resize(m_pUdpSocket->pendingDatagramSize());
            //m_pUdpSocket->readDatagram(datagram.data(), datagram.size());
            qDebug() << "Received data: " << datagram;
            // 将16进制QByteArray转换为QString表示
            QString result = QString::asprintf("%s", datagram.toHex().toUpper().constData());
            qDebug() << "Received result: " << result;
            showMessage(QString("mes:%1\n").arg(result));
        //}
    });



#if (QT_VERSION <= QT_VERSION_CHECK(5,15,0))
    connect(client,QOverload<QAbstractSocket::SocketError>::of(&QAbstractSocket::error), this, [this]{
        qDebug() << "Socket Error:" << client->errorString();
        showMessage(QString("Socket Error:%1\n").arg(client->errorString()));
    });
#else
    connect(this,&QAbstractSocket::errorOccurred,this,&ClientSocket::slotErr);
#endif

}

SimpleQTcpClient::~SimpleQTcpClient()
{
    if(client->state() == QAbstractSocket::ConnectedState){
        client->disconnectFromHost();
    }
}

void SimpleQTcpClient::showMessage(QString message)
{
    messageTextEdit->insertPlainText(message);
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/从前慢现在也慢/article/detail/930646
推荐阅读
相关标签
  

闽ICP备14008679号