Qt中TCP协议通信详解

 更新时间:2022年08月19日 17:04:54   作者:码灵薯  
这篇文章主要为大家详细介绍了Qt中TCP协议通信,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

TCP协议是经常使用的通信方式。在QT中做了非常友好的封装,使用非常方便。

需要添加的模块:network

Qt中的TCP类:QTcpSocket , QTcpServer

常用函数介绍

连接目标地址和端口

virtual void QTcpSocket ::connectToHost(const QHostAddress &address, quint16 port, OpenMode mode = ReadWrite);

  • 发送数据

inline qint64 QTcpSocket ::write(const QByteArray &data)

  • 监听某个地址和端口号

bool QTcpServer::listen(const QHostAddress &address = QHostAddress::Any, quint16 port = 0);

  • 有新的连接信号

void QTcpServer::newConnection();

  • 是否有新的连接

virtual bool QTcpServer::hasPendingConnections() const;

  • 获取新的连接,必须处理完才能继续接收到连接

virtual QTcpSocket *QTcpServer::nextPendingConnection();

  • 收到新的数据信号

void QTcpSocket::readyRead();

  • 读取收到的数据,必须读取完才能继续接收

QByteArray readAll();

使用案例(example)

客户端

#include <QTcpSocket>
#include <QWidget>
#include <QLineEdit>
class Client : public QWidget
{
    Q_OBJECT
public:
    Client(QWidget *parent);

public slots:
    void slotSendButtonClick();
private:
    QTcpSocket *_socket;
    QLineEdit *_lineEdit;
    bool _isConnected;
};
#include "client.h"
#include <QPushButton>
#include <QHBoxLayout>
Client::Client(QWidget *parent)
    : QWidget(parent)
{
    _socket = new QTcpSocket(this);

    _lineEdit = new QLineEdit(this);
    QPushButton *sendButton = new QPushButton("send");
    connect(sendButton, SIGNAL(clicked()), this, SLOT(slotSendButtonClick()));
    connect(_lineEdit, SIGNAL(returnPressed()), this, SLOT(slotSendButtonClick()));
    
    QHBoxLayout *lay = new QHBoxLayout(this);
    lay->addWidget(_lineEdit);
    lay->addWidget(sendButton);

    _isConnected = false;
}

void Client::slotSendButtonClick()
{
    if (!_isConnected)
    {
        _socket->connectToHost("127.0.0.1", 9988);
        _isConnected = true;
    }
    QString text = _lineEdit->text();
    if (!text.isEmpty())
    {
        _socket->write(text.toUtf8());//发送数据
        _lineEdit->clear();
    }
}

服务端

#include <QWidget>
#include <QTcpServer>
#include <QTcpSocket>
class QTextBrowser;
class Server :public QWidget
{
    Q_OBJECT
public:
    Server(QWidget *parent);
public slots:
    void slotCurrentIndexChanged(const QString&);
    void slotNewConnection();
private:
    QTcpServer *_server;
    QTcpSocket *_socket;
    QTextBrowser *_textBrowser;
};
#include "server.h"
#include <QHostAddress>
#include <QTextBrowser>
#include <QByteArray>
#include <QGridLayout>
#include <QNetworkInterface>
#include <QComboBox>
Server::Server(QWidget *parent)
{
    _server = new QTcpServer(this);
    //_server->listen(QHostAddress::Any, 9988);//监听跟本主机相连的所有网口
    connect(_server, SIGNAL(newConnection()),this, SLOT(slotNewConnection()) );

    QList<QHostAddress> addrList = QNetworkInterface::allAddresses();
    QComboBox *comboBox = new QComboBox;
    for (const QHostAddress& addr : addrList)
    {
        quint32 ipAddr = addr.toIPv4Address();
        if (ipAddr != 0)
        {
            comboBox->addItem(QHostAddress(ipAddr).toString());
        }
    }
    connect(comboBox, SIGNAL(currentIndexChanged(const QString&)), this, SLOT(slotCurrentIndexChanged(const QString&)));


    _textBrowser = new QTextBrowser(this);
    QGridLayout *lay = new QGridLayout(this);
    lay->addWidget(comboBox, 0, 0);
    lay->addWidget(_textBrowser,1,0);
}

void Server::slotCurrentIndexChanged(const QString& item)
{
    if (!_server->isListening())
    {
        _server->listen(QHostAddress(item), 9988);
    }
    
    _textBrowser->append("listen...");
}

void Server::slotNewConnection()
{
    _textBrowser->append("connecting...");
    while (_server->hasPendingConnections())//必须处理完所有的连接,否则有新连接时就不会在发信号过来
    {
        _socket = _server->nextPendingConnection();
        connect(_socket, &QTcpSocket::readyRead, [&]() {
            _textBrowser->append("receive message...");
            QByteArray newMessage = _socket->readAll();
            _textBrowser->append(QString(newMessage));
        });
    }
}

使用效果

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

相关文章

  • C语言用fstat函数获取文件的大小方法

    C语言用fstat函数获取文件的大小方法

    今天小编就为大家分享一篇关于C语言用fstat函数获取文件的大小方法,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧
    2018-12-12
  • 解析使用C++编写无错代码的方法技巧

    解析使用C++编写无错代码的方法技巧

    本篇文章是对使用C++编写无错代码的方法进行了详细的分析介绍,需要的朋友参考下
    2013-05-05
  • 解析C++中的虚拟函数及其静态类型和动态类型

    解析C++中的虚拟函数及其静态类型和动态类型

    虚拟函数(Visual Function)亦常被成为虚函数,是C++中的一个重要特性,本文我们就来解析C++中的虚拟函数及其静态类型和动态类型
    2016-06-06
  • C++任意线程通过hwnd实现将操作发送到UI线程执行

    C++任意线程通过hwnd实现将操作发送到UI线程执行

    做Windows界面开发时,经常需要在多线程环境中将操作抛到主线程执行,下面我们就来学习一下如何在不需要重新定义消息以及接收消息的情况下实现这一要求,感兴趣的可以了解下
    2024-03-03
  • C语言如何求整数的位数及各位数字之和

    C语言如何求整数的位数及各位数字之和

    这篇文章主要介绍了C语言如何求整数的位数及各位数字之和,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-11-11
  • C语言算法打卡回文串验证算法题解

    C语言算法打卡回文串验证算法题解

    这篇文章主要为大家介绍了C语言算法打卡万人千提的leetcode回文串的验证算法题解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步
    2022-02-02
  • C++发送HTTP请求的实现代码

    C++发送HTTP请求的实现代码

    这篇文章主要介绍了C++发送HTTP请求的实现代码,需要的朋友可以参考下
    2014-06-06
  • C++使用chrono库处理日期和时间的实现方法

    C++使用chrono库处理日期和时间的实现方法

    C++11 中提供了日期和时间相关的库 chrono,通过 chrono 库可以很方便地处理日期和时间,本文主要介绍了C++使用chrono库处理日期和时间的实现方法,感兴趣的小伙伴们可以参考一下
    2021-09-09
  • C++ 让函数返回数组的方法

    C++ 让函数返回数组的方法

    这篇文章主要介绍了C++ 让函数返回数组的方法,文中讲解非常细致,代码帮助大家更好的理解和学习,感兴趣的朋友可以了解下
    2020-07-07
  • C中的volatile使用方法

    C中的volatile使用方法

    volatile 影响编译器编译的结果,指出,volatile 变量是随时可能发生变化的,与volatile变量有关的运算,不要进行编译优化,以免出错
    2013-02-02

最新评论