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++编程的相关文件操作

    解读C++编程的相关文件操作

    这篇文章主要介绍了解读C++编程的相关文件操作,是C++入门学习中的基础知识,需要的朋友可以参考下
    2015-09-09
  • C语言中char*和char[]用法区别分析

    C语言中char*和char[]用法区别分析

    这篇文章主要介绍了C语言中char*和char[]用法区别,包括使用过程中的误区及注意点分析,需要的朋友可以参考下
    2014-09-09
  • C语言结构体的全方面解读

    C语言结构体的全方面解读

    C 数组允许定义可存储相同类型数据项的变量,结构是 C 编程中另一种用户自定义的可用的数据类型,它允许你存储不同类型的数据项
    2021-10-10
  • C++关于指针,继承和多态介绍

    C++关于指针,继承和多态介绍

    大家好,本篇文章主要讲的是C++关于指针,继承和多态介绍,感兴趣的同学赶快来看一看吧,对你有帮助的话记得收藏一下,方便下次浏览
    2022-01-01
  • C++开发截屏小程序功能

    C++开发截屏小程序功能

    这篇文章主要介绍了C++开发截屏小程序功能,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2020-04-04
  • c++获取进程信息列表和进程所调用的dll列表

    c++获取进程信息列表和进程所调用的dll列表

    这篇文章主要介绍了c++获取进程信息列表和进程所调用的dll列表,大家参考使用吧
    2013-11-11
  • C语言菜鸟基础教程之a++与++a

    C语言菜鸟基础教程之a++与++a

    很多同学在学习c语言的时候是不是会碰到a++和++a都有甚么作用啊。今天我们就来探讨下
    2017-10-10
  • C++中nullptr 和 NULL 的区别及用法

    C++中nullptr 和 NULL 的区别及用法

    nullptr是常数,nullptr_t是它的类型.在需要分别使用空指针或空指针类型的上下文中使用每一个.今天通过本文给大家介绍C++ nullptr 和 NULL 的使用区别,需要的朋友参考下吧
    2021-07-07
  • c++中inline的用法分析

    c++中inline的用法分析

    本篇文章是对c++中inline的用法进行了详细的分析介绍,需要的朋友参考下
    2013-05-05
  • c语言二进制数按位输出示例

    c语言二进制数按位输出示例

    这篇文章主要介绍了c语言二进制数按位输出示例,需要的朋友可以参考下
    2014-03-03

最新评论