Qt 实现简单的tcp网络通信

这篇具有很好参考价值的文章主要介绍了Qt 实现简单的tcp网络通信。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。


背景:
最近计网要结课了,匆忙之间有个计网实验还没做。
上网这里查查那里查查,随便搞搞
然后在 这篇文章里找到了能够实现的代码
自己想着把它图形化一下,最后在超级棒棒糖的帮助下实现了。

成品效果图:

Qt 实现简单的tcp网络通信

代码:

工具头文件tool.h

该头文件用于添加一些要用到的库,直接引用这个库,比较方便美观

#ifndef TOOL_H
#define TOOL_H
#include<winsock2.h>
#include<QDateTime>

#include <ws2tcpip.h>
#include <stdio.h>
#include <QDebug>

#include <QNetworkInterface>
#include <QNetworkInterface>
#include <QDebug>
#include <QtNetwork>


#endif // TOOL_H

UI文件代码 ui_widget.h:

/********************************************************************************
** Form generated from reading UI file 'widget.ui'
**
** Created by: Qt User Interface Compiler version 5.12.2
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/

#ifndef UI_WIDGET_H
#define UI_WIDGET_H

#include <QtCore/QVariant>
#include <QtWidgets/QApplication>
#include <QtWidgets/QFrame>
#include <QtWidgets/QGroupBox>
#include <QtWidgets/QHBoxLayout>
#include <QtWidgets/QLabel>
#include <QtWidgets/QLineEdit>
#include <QtWidgets/QTextBrowser>
#include <QtWidgets/QTextEdit>
#include <QtWidgets/QToolButton>
#include <QtWidgets/QWidget>

QT_BEGIN_NAMESPACE

class Ui_Widget
{
public:
    QLabel *label;
    QTextBrowser *SeverState;
    QFrame *line;
    QToolButton *send;
    QFrame *line_2;
    QTextBrowser *talk;
    QWidget *horizontalLayoutWidget;
    QHBoxLayout *horizontalLayout;
    QLabel *label_2;
    QLineEdit *posline;
    QToolButton *Open;
    QGroupBox *groupBox;
    QLabel *label_3;
    QLineEdit *TheIp;
    QLabel *label_4;
    QLineEdit *TheHost;
    QToolButton *connectIp;
    QTextBrowser *Showip;
    QLabel *label_5;
    QTextBrowser *connectState;
    QTextEdit *TextCin;

    void setupUi(QWidget *Widget)
    {
        if (Widget->objectName().isEmpty())
            Widget->setObjectName(QString::fromUtf8("Widget"));
        Widget->resize(1106, 823);
        label = new QLabel(Widget);
        label->setObjectName(QString::fromUtf8("label"));
        label->setGeometry(QRect(20, 180, 131, 41));
        label->setStyleSheet(QString::fromUtf8("font:20px"));
        SeverState = new QTextBrowser(Widget);
        SeverState->setObjectName(QString::fromUtf8("SeverState"));
        SeverState->setGeometry(QRect(10, 240, 271, 131));
        line = new QFrame(Widget);
        line->setObjectName(QString::fromUtf8("line"));
        line->setGeometry(QRect(350, 610, 761, 21));
        line->setFrameShape(QFrame::HLine);
        line->setFrameShadow(QFrame::Sunken);
        send = new QToolButton(Widget);
        send->setObjectName(QString::fromUtf8("send"));
        send->setGeometry(QRect(940, 720, 151, 71));
        send->setStyleSheet(QString::fromUtf8("font:30px"));
        line_2 = new QFrame(Widget);
        line_2->setObjectName(QString::fromUtf8("line_2"));
        line_2->setGeometry(QRect(340, 0, 31, 821));
        line_2->setFrameShape(QFrame::VLine);
        line_2->setFrameShadow(QFrame::Sunken);
        talk = new QTextBrowser(Widget);
        talk->setObjectName(QString::fromUtf8("talk"));
        talk->setGeometry(QRect(370, 20, 721, 571));
        horizontalLayoutWidget = new QWidget(Widget);
        horizontalLayoutWidget->setObjectName(QString::fromUtf8("horizontalLayoutWidget"));
        horizontalLayoutWidget->setGeometry(QRect(0, 80, 351, 71));
        horizontalLayout = new QHBoxLayout(horizontalLayoutWidget);
        horizontalLayout->setSpacing(6);
        horizontalLayout->setContentsMargins(11, 11, 11, 11);
        horizontalLayout->setObjectName(QString::fromUtf8("horizontalLayout"));
        horizontalLayout->setContentsMargins(0, 0, 0, 0);
        label_2 = new QLabel(horizontalLayoutWidget);
        label_2->setObjectName(QString::fromUtf8("label_2"));
        label_2->setStyleSheet(QString::fromUtf8("font:25px;"));

        horizontalLayout->addWidget(label_2);

        posline = new QLineEdit(horizontalLayoutWidget);
        posline->setObjectName(QString::fromUtf8("posline"));

        horizontalLayout->addWidget(posline);

        Open = new QToolButton(horizontalLayoutWidget);
        Open->setObjectName(QString::fromUtf8("Open"));
        Open->setStyleSheet(QString::fromUtf8("font:30px"));

        horizontalLayout->addWidget(Open);

        groupBox = new QGroupBox(Widget);
        groupBox->setObjectName(QString::fromUtf8("groupBox"));
        groupBox->setGeometry(QRect(10, 390, 301, 261));
        groupBox->setStyleSheet(QString::fromUtf8("font:20px"));
        label_3 = new QLabel(groupBox);
        label_3->setObjectName(QString::fromUtf8("label_3"));
        label_3->setGeometry(QRect(10, 30, 221, 31));
        TheIp = new QLineEdit(groupBox);
        TheIp->setObjectName(QString::fromUtf8("TheIp"));
        TheIp->setGeometry(QRect(10, 60, 281, 31));
        label_4 = new QLabel(groupBox);
        label_4->setObjectName(QString::fromUtf8("label_4"));
        label_4->setGeometry(QRect(10, 110, 151, 41));
        TheHost = new QLineEdit(groupBox);
        TheHost->setObjectName(QString::fromUtf8("TheHost"));
        TheHost->setGeometry(QRect(10, 160, 281, 31));
        connectIp = new QToolButton(groupBox);
        connectIp->setObjectName(QString::fromUtf8("connectIp"));
        connectIp->setGeometry(QRect(20, 210, 161, 41));
        Showip = new QTextBrowser(Widget);
        Showip->setObjectName(QString::fromUtf8("Showip"));
        Showip->setGeometry(QRect(115, 10, 231, 41));
        label_5 = new QLabel(Widget);
        label_5->setObjectName(QString::fromUtf8("label_5"));
        label_5->setGeometry(QRect(10, 10, 101, 41));
        label_5->setStyleSheet(QString::fromUtf8("font:25px"));
        connectState = new QTextBrowser(Widget);
        connectState->setObjectName(QString::fromUtf8("connectState"));
        connectState->setGeometry(QRect(30, 660, 256, 151));
        TextCin = new QTextEdit(Widget);
        TextCin->setObjectName(QString::fromUtf8("TextCin"));
        TextCin->setGeometry(QRect(360, 620, 561, 191));

        retranslateUi(Widget);

        QMetaObject::connectSlotsByName(Widget);
    } // setupUi

    void retranslateUi(QWidget *Widget)
    {
        Widget->setWindowTitle(QApplication::translate("Widget", "\345\260\217chat", nullptr));
        label->setText(QApplication::translate("Widget", "\346\234\215\345\212\241\347\253\257\347\212\266\346\200\201\357\274\232", nullptr));
        send->setText(QApplication::translate("Widget", "\345\217\221\351\200\201", nullptr));
        label_2->setText(QApplication::translate("Widget", "\346\234\215\345\212\241\345\231\250\345\274\200\346\224\276\347\253\257\345\217\243", nullptr));
        Open->setText(QApplication::translate("Widget", "\346\211\223\345\274\200", nullptr));
        groupBox->setTitle(QApplication::translate("Widget", "\350\277\236\346\216\245\345\214\272", nullptr));
        label_3->setText(QApplication::translate("Widget", "\345\257\271\346\226\271\346\234\215\345\212\241\345\231\250ip\357\274\232", nullptr));
        label_4->setText(QApplication::translate("Widget", "\345\257\271\346\226\271\346\234\215\345\212\241\347\253\257\345\217\243\357\274\232", nullptr));
        connectIp->setText(QApplication::translate("Widget", "\350\277\236\346\216\245", nullptr));
        label_5->setText(QApplication::translate("Widget", "\346\234\254\346\234\272ip:", nullptr));
    } // retranslateUi

};

namespace Ui {
    class Widget: public Ui_Widget {};
} // namespace Ui

QT_END_NAMESPACE

#endif // UI_WIDGET_H

窗口头文件 widget.h:

#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>
#include "tool.h"

namespace Ui {
class Widget;
}

class Widget : public QWidget
{
    Q_OBJECT

public:
    explicit Widget(QWidget *parent = nullptr);

    ~Widget();

private:
    Ui::Widget *ui;
    QTcpServer server;     //TCP控制本地服务器
    quint16 host;           //开放端口
    QTcpSocket *socket = new QTcpSocket(this);     //连接其他的Socket
    QTcpSocket *so = new QTcpSocket(this);         //被连接的Socket
    QString AimIp;
    quint16 AimPort;


private slots:
    void openHost(); //开放某个端口
    void toConnect(); //连接端口
    void toSend();      //发送信息
};

#endif // WIDGET_H

窗口源文件widget.cpp:

#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
    QList<QHostAddress> list = QNetworkInterface::allAddresses();
    for(int nIter=0; nIter<list.count(); nIter++)
    {
        if(!list[nIter].isLoopback())
        {
            if(list[nIter].protocol() == QAbstractSocket::IPv4Protocol )
            {
                qDebug() << list[nIter].toString();
                ui->Showip->append(list[nIter].toString());
            }
        }
    }

    connect(ui->Open, &QToolButton::clicked,this, &Widget::openHost);//打开端口
    connect(ui->connectIp, &QToolButton::clicked,this,&Widget::toConnect);//连接
    connect(ui->send, &QToolButton::clicked, this,&Widget::toSend);
    //被连接
    connect(&server, &QTcpServer::newConnection, this, [=]() {
        so = server.nextPendingConnection();
        QString ip = so->peerAddress().toString();
        quint16 port = so->peerPort();
        qDebug() << "New connection from " << ip << ":" << port;

        QString m = "<font color='blue'>有新的连接来自"+ip+":"+QString::number(port)+"</font>";
        ui->SeverState->append(m);
        //被连接后接收信息:
        connect(so, &QTcpSocket::readyRead, this, [=]() {
            QDateTime currentDateTime = QDateTime::currentDateTime();
            QString ip = so->peerAddress().toString();
            QByteArray data = so->readAll();
            qDebug() << "Received data:" << data;
            QString mag1 = QString::fromUtf8(data);
            qDebug()<<currentDateTime;
            QString strDateTime = currentDateTime.toString("yyyy-MM-dd hh:mm:ss");
            QString mag = "<font color='blue'>"+strDateTime+"收到来自"+ip+"的消息:"+mag1+"</font>";
            ui->talk->append(mag);
        });
    });


    //连接成功:
    connect(socket, &QTcpSocket::connected, this, [=]() {
        qDebug() << "Connected to server.";

        // 发送信息给服务端
        QByteArray message = "连接你了";
        socket->write(message);
    });

    // 接收服务端发送的信息
    connect(socket, &QTcpSocket::readyRead, this, [=]() {
        QDateTime currentDateTime = QDateTime::currentDateTime();
        QString strDateTime = currentDateTime.toString("yyyy-MM-dd hh:mm:ss");
        QString ip = socket->peerAddress().toString();
        QByteArray data = socket->readAll();
        QString message = QString::fromUtf8(data);
        qDebug() << "Received message from server:" << message;
        QString mag = "<font color='blue'>"+strDateTime+"收到来自"+ip+"的消息:"+message+"</font>";
        ui->talk->append(mag);
    });


}



void Widget::openHost(){
    int temp = this->ui->posline->text().toInt();
    this->host = static_cast<quint16>(temp);
    qDebug()<<"端口:"<<this->host<<endl;

    server.close();
    if(!this->server.listen(QHostAddress::Any, this->host)){
        qDebug()<<"端口开放失败"<<endl;
        this->ui->SeverState->append("<font color='red'>端口开放失败</font>");
    }
    else{
        this->ui->SeverState->append(this->ui->posline->text()+"端口已开放");
    }

}

void Widget::toConnect(){

    AimIp = ui->TheIp->text();
    int h = ui->TheHost->text().toInt();
    AimPort = static_cast<quint16>(h);
    socket->connectToHost(AimIp,AimPort);
    if (socket->waitForConnected()) {
        // 连接成功
        qDebug() << "Connected to server!";
        QString mag = "连接"+this->AimIp+"的端口"+ui->TheHost->text()+"成功";
        ui->connectState->append(mag);



    } else {
        // 连接失败
        QString mag = "连接"+this->AimIp+"的端口"+ui->TheHost->text()+"失败";
        qDebug() << "Failed to connect to server: " << socket->errorString();
        mag = "<font color='red'>"+mag+"</font>";
        ui->connectState->append(mag);
    }
}

void Widget::toSend(){
    QString mag = this->ui->TextCin->toPlainText();
    so->write(mag.toUtf8());
    so->flush();
    so->waitForBytesWritten();
    socket->write(mag.toUtf8());
    socket->flush();
    socket->waitForBytesWritten();
    QDateTime currentDateTime = QDateTime::currentDateTime();
    QString strDateTime = currentDateTime.toString("yyyy-MM-dd hh:mm:ss");
    QString smag = strDateTime+"向"+this->AimIp+"发送消息:"+mag;
    ui->talk->append(smag);
    ui->TextCin->clear();
}


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

相关代码说明:

Qt获取本机ip:

	QList<QHostAddress> list = QNetworkInterface::allAddresses();
    for(int nIter=0; nIter<list.count(); nIter++)
    {
        if(!list[nIter].isLoopback())
        {
            if(list[nIter].protocol() == QAbstractSocket::IPv4Protocol )
            {
                qDebug() << list[nIter].toString();//输出端口信息
            }
        }
    }
    

Qt 打开,监视服务端端口:

QTcpServer server;
quint16 host = 8080;
server.listen(QHostAddress::Any, host);

这里的listen()函数则是打开端口并监视,不过要注意,一个server只能打开监视一个端口。

Qt 客户端连接服务端:

这里的客户端其实也就是你自己的主机,你自己的主机也可以充当服务端捏。

	QString AimIp = "127.0.0.1"
    quint16 AimPort = 8080;
    QTcpSocket *socket = new QTcpSocket();
    socket->connectToHost(AimIp,AimPort);//连接函数
    if (socket->waitForConnected()) {
        // 连接成功
        qDebug() << "Connected to server!";

    } else {
        // 连接失败
        qDebug() << "连接失败";
    }

Qt 服务端被连接后接收显示并接收消息:

connect(&server, &QTcpServer::newConnection, this, [=]() {
        so = server.nextPendingConnection();
        QString ip = so->peerAddress().toString();
        quint16 port = so->peerPort();
        qDebug() << "New connection from " << ip << ":" << port;

        QString m = "<font color='blue'>有新的连接来自"+ip+":"+QString::number(port)+"</font>";
        ui->SeverState->append(m);
        //被连接后接收信息:
        connect(so, &QTcpSocket::readyRead, this, [=]() {
            QDateTime currentDateTime = QDateTime::currentDateTime();
            QString ip = so->peerAddress().toString();
            QByteArray data = so->readAll();//获取消息
            qDebug() << "Received data:" << data;
            QString mag1 = QString::fromUtf8(data);
            qDebug()<<currentDateTime;
            QString strDateTime = currentDateTime.toString("yyyy-MM-dd hh:mm:ss");
            QString mag = "<font color='blue'>"+strDateTime+"收到来自"+ip+"的消息:"+mag1+"</font>";
            ui->talk->append(mag);
        });
    });

Qt 发送消息:

主要通过QTcpSocket的write()函数进行发送消息。

void Widget::toSend(){
    QString mag = this->ui->TextCin->toPlainText();
    so->write(mag.toUtf8());
    so->flush();
    so->waitForBytesWritten();
    socket->write(mag.toUtf8());
    socket->flush();
    socket->waitForBytesWritten();
    QDateTime currentDateTime = QDateTime::currentDateTime();
    QString strDateTime = currentDateTime.toString("yyyy-MM-dd hh:mm:ss");
    QString smag = strDateTime+"向"+this->AimIp+"发送消息:"+mag;
    ui->talk->append(smag);
    ui->TextCin->clear();
}

最后:

这个东东只能进行简单的tcp通讯,而且要求连接的是同一局域网的两台设备才能进行交流,不过也的确是这样的,除非你有额外的设备什么的~
当然,如果你想整个QQ那种的东西出来的话,可以整个中间服务器,然后让不同的客户端都访问那个中间服务器,通过中间服务器进行交流~文章来源地址https://www.toymoban.com/news/detail-429704.html

到了这里,关于Qt 实现简单的tcp网络通信的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • QT网络通信-TCP、UDP通信

    时间记录:2024/1/17 pro文件添加模块network (1)创建TCP服务器对象 QTcpServer (2)为 QTcpServer 对象的 newConnection 信号绑定槽,用来监听TCP客户端的新连接,有新的客户端连接便会触发此信号 (3)使用 nextPendingConnection 方法获取连接的Tcp客户端对象 QTcpSocket (4)为 QTcpSocket 的 r

    2024年01月18日
    浏览(41)
  • QT 中基于 TCP 的网络通信 (备查)

    基于 TCP 的套接字通信需要用到两个类: 1) QTcpServer :服务器类,用于监听客户端连接以及和客户端建立连接。 2) QTcpSocket :通信的套接字类,客户端、服务器端都需要使用。 这两个套接字通信类都属于网络模块 network 。 TCP协议是 双向连接,双向断开,即 三次握手,四次

    2024年02月03日
    浏览(37)
  • Qt开发-TCP/IP网络通信(以及文件传输)

    TCP/IP通信(即SOCKET通信)是通过网线将 服务器Server端 和 客户机Client端 进行连接,在遵循ISO/OSI模型的四层层级构架的基础上通过TCP/IP协议建立的通讯。控制器可以设置为服务器端或客户端。 关于TCP/IP协议可详看:TCP/IP协议详解 - 知乎 (zhihu.com) 总的来说,TCP/IP通讯有两个部分

    2024年02月10日
    浏览(39)
  • QT C++ 基于TCP通信的网络聊天室

    .ui .pro 在pro文件中添加network库 .h .main .cpp .ui .pro 在pro文件中添加network库 .h .main .cpp        

    2024年02月09日
    浏览(43)
  • 【网络原理】使用Java基于TCP搭建简单客户端与服务器通信

    TCP服务器与客户端的搭建需要借助以下API ServerSocket 是创建TCP服务端Socket的API。 ServerSocket 构造方法 : 方法签名 方法说明 ServerSocket(int port) 创建一个服务端流套接字Socket,并绑定到指定端口 ServerSocket 方法: 方法签名 方法说明 Socket accept() 开始监听指定端口(创建时绑定的端

    2024年03月12日
    浏览(67)
  • 基于UDP/TCP的网络通信编程实现

    红色是心中永不褪色的赤诚 操作系统为网络编程提供了 Socket api , Socket是基于TCP/IP协议的网络通信的基本单元, 基于Socket的网络程序开发就是 网络编程. 由于直接与应用层联系的是传输层, 所以针对应用层协议(TCP, UDP), Shocket提供了三种套接字, 分别是 流套接字(使用TCP) , 数据报

    2024年02月08日
    浏览(37)
  • Linux下套接字TCP实现网络通信

    ​ 套接字(Socket) 是计算机网络中实现网络通信的一种 编程接口 。它提供了应用程序与网络通信之间的一座桥梁,因为它允许应用程序通过网络发送和接收相应的数据以实现不同主机之间的通信。 通常套接字由以下两部分组成: 1.网络IP和端口号 :IP用来标识主机,而端口号

    2024年02月10日
    浏览(32)
  • 使用 python socket 实现UDP/TCP网络通信

    目录 目录 1.socket简介 2.创建socket 2.1创建UDPSocket 2.2创建TCPSocket 3.使用UDPSocket发送数据并接收 4.使用UDPSocket发送广播 5.UDPSocket聊天器 (多线程实现消息的收发功能) 6.使用TCPSocket建立客户端 7.使用TCPSocket建立服务端        socket(简称:套接字),是支持TCP和UDP(网络传输方式

    2023年04月10日
    浏览(49)
  • Java TCP长连接详解:实现稳定、高效的网络通信

    在现代互联网应用中,稳定而高效的网络通信是至关重要的。而TCP长连接作为一种常见的通信机制,允许客户端和服务器之间保持长时间的连接,有效地传输数据。本文将详细介绍Java中TCP长连接的概念、优点、适用场景,并结合实际案例进行分析。 TCP长连接是一种建立在T

    2024年02月03日
    浏览(39)
  • 【QT网络编程】实现UDP协议通信

    Internet 协议集支持一个无连接的传输协议,该协议称为用户数据报协议(UDP,User Datagram Protocol)。UDP 为应用程序提供了 一种无需建立连接就可以发送封装的 IP 数据包的方法 。RFC 768 描述了 UDP。 UDP协议根据消息传送模式可以分为: 单播(Unicast)、组播(Multicast)和广播(

    2024年02月02日
    浏览(40)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包