QT 网络编程 8

2024-03-03 17:04
文章标签 qt 编程 网络

本文主要是介绍QT 网络编程 8,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

1 基础知识

udp 

 

tcp 

2 UDP

框架

客户端:
QUdpSocket x;
qint64 writeDatagram(
const char *data,
qint64 size, 
const QHostAddress &address, 
quint16 port
);服务器:
void Server::initSocket(){udpSocket = new QUdpSocket(this);udpSocket->bind(QHostAddress::LocalHost, 7755);connect(udpSocket, SIGNAL(readyRead()),this, SLOT(readPendingDatagrams()));}

2.1 客户端示例:

网络编程都需添加network(后面不再提醒)

widget.h 

#ifndef WIDGET_H
#define WIDGET_H#include <QWidget>
#include <QTextEdit>
#include <QLineEdit>
#include <QPushButton>
#include <QUdpSocket>
#include <QHostAddress>class Widget : public QWidget
{Q_OBJECT
public slots:void senddata(){udpsock->writeDatagram(le->text().toStdString().c_str(), QHostAddress("192.168.31.124"), 8888);}void recvdata(){QByteArray datagram;datagram.resize(udpsock->pendingDatagramSize());QHostAddress sender;quint16 senderPort;udpsock->readDatagram(datagram.data(), datagram.size(),&sender, &senderPort);te->append(datagram);}
public:Widget(QWidget *parent = 0);~Widget();
private:QTextEdit *te;QLineEdit *le;QPushButton *pb;QUdpSocket *udpsock;
};#endif // WIDGET_H

widget.cpp

#include "widget.h"
#include <QVBoxLayout>Widget::Widget(QWidget *parent): QWidget(parent)
{te = new QTextEdit;le = new QLineEdit;pb = new QPushButton("send");QVBoxLayout *vbox = new QVBoxLayout;vbox->addWidget(te);vbox->addWidget(le);vbox->addWidget(pb);setLayout(vbox);udpsock = new QUdpSocket;connect(pb, SIGNAL(clicked(bool)), this, SLOT(senddata()));connect(udpsock, SIGNAL(readyRead()), this, SLOT(recvdata()));
}Widget::~Widget()
{}

2.2 服务端

添加network

udpserver.h

#ifndef UDPSERVER_H // 如果UDPSERVER_H没有被定义
#define UDPSERVER_H // 定义UDPSERVER_H#include <QObject> // 包含QObject的头文件,QObject是所有Qt对象的基类
#include <QUdpSocket> // 包含QUdpSocket的头文件,用于UDP通信
#include <QDebug> // 包含QDebug的头文件,用于在调试时输出信息// 声明udpServer类,继承自QObject
class udpServer : public QObject
{Q_OBJECT // 启用Qt的信号和槽机制
public:explicit udpServer(QObject *parent = 0); // 构造函数,explicit防止隐式转换,可选的parent参数默认为0void init() // 初始化函数{udpSocket = new QUdpSocket(this); // 创建QUdpSocket对象udpSocket->bind(QHostAddress::AnyIPv4, 8888); // 绑定到任意IPv4地址的8888端口// 连接QUdpSocket的readyRead信号到本类的readPendingDatagrams槽,当有数据可读时触发connect(udpSocket, SIGNAL(readyRead()),this, SLOT(readPendingDatagrams()));qDebug()<<"init...."; // 使用QDebug输出初始化信息}
signals: // 信号部分,此处未定义任何信号public slots: // 槽部分void readPendingDatagrams() // 当有数据待读取时,会调用此函数{while (udpSocket->hasPendingDatagrams()) { // 循环处理所有待读取的数据报QByteArray datagram; // 用于存储接收到的数据报datagram.resize(udpSocket->pendingDatagramSize()); // 调整大小以匹配待读取数据报的大小QHostAddress sender; // 发送者的地址quint16 senderPort; // 发送者的端口// 读取数据报,并保存发送者的地址和端口udpSocket->readDatagram(datagram.data(), datagram.size(),&sender, &senderPort);//processTheDatagram(datagram); // 处理数据报的函数qDebug()<<"recv: "<<datagram; // 使用QDebug输出接收到的数据报// 将接收到的数据报原样发送回去udpSocket->writeDatagram(datagram.data(), datagram.size(),sender, senderPort);}}private:QUdpSocket *udpSocket; // 指向QUdpSocket对象的指针
};#endif // UDPSERVER_H // 结束预处理器指令

udpserver.cpp

#include "udpserver.h"udpServer::udpServer(QObject *parent) : QObject(parent)
{}

main.cpp

#include <QCoreApplication>
#include <udpserver.h>int main(int argc, char *argv[])
{QCoreApplication a(argc, argv);udpServer server;server.init();return a.exec();
}

最终效果:

3 TCP

框架

客户端:
mytcpsock = new QTcpSocket;
Mytcpsock->connectToHost(
QHostAddress("192.168.4.222"), 8888);connect(mytcpsock, SIGNAL(readyRead()), this, SLOT(read_data()));服务器:
Server::Server(QObject *parent) : QObject(parent)
{tcpserver = new QTcpServer;tcpserver->listen(QHostAddress::AnyIPv4, 8888);connect(tcpserver, SIGNAL(newConnection()),this, SLOT(new_client()));tcpserver->waitForNewConnection();
}

3.1 客户端

widget.h

#ifndef WIDGET_H
#define WIDGET_H#include <QWidget>
#include <QLineEdit>
#include <QPushButton>
#include <QTextEdit>
#include <QTcpSocket>class Widget : public QWidget
{Q_OBJECT
public slots:void senddata(){tcpsocket->write(le->text().toStdString().c_str());}void recvdata(){QByteArray buf = tcpsocket->readAll();te->append(buf);}public:Widget(QWidget *parent = 0);~Widget();
private:QLineEdit *le;QPushButton *pb;QTextEdit *te;QTcpSocket *tcpsocket;
};#endif // WIDGET_H

widget.cpp

#include "widget.h"
#include <QVBoxLayout>
#include <QHostAddress>Widget::Widget(QWidget *parent): QWidget(parent)
{le = new QLineEdit;pb = new QPushButton("senddata");te = new QTextEdit;QVBoxLayout *vbox = new QVBoxLayout;vbox->addWidget(te);vbox->addWidget(le);vbox->addWidget(pb);setLayout(vbox);tcpsocket = new QTcpSocket;//connect to servertcpsocket->connectToHost(QHostAddress("192.168.1.155"), 8888);connect(pb, SIGNAL(clicked(bool)), this, SLOT(senddata()));connect(tcpsocket, SIGNAL(readRead()), this, SLOT(recvdata()));}Widget::~Widget()
{}

main.cpp

#include "widget.h"
#include <QApplication>int main(int argc, char *argv[])
{QApplication a(argc, argv);Widget w;w.show();return a.exec();
}

3.2 服务端

tcpServer.h

#ifndef TCPSERVER_H
#define TCPSERVER_H#include <QObject>
#include <QTcpServer>
#include <QTcpSocket>
#include <QHostAddress>
#include <QDebug>class TcpServer : public QObject
{Q_OBJECT // 启用Qt的信号和槽机制
public:explicit TcpServer(QObject *parent = 0);
public slots:void newConnected(){qDebug() << "connected";clientsock = ser->nextPendingConnection(); //得到客户端connect(clientsock, SIGNAL(readyRead()), this, SLOT(recvData()));}void recvData(){QByteArray buf = clientsock->readAll();qDebug()<<"recv:"<<buf;clientsock->write(buf);}private:QTcpServer *ser;QTcpSocket *clientsock;};#endif // TCPSERVER_H

tcpServer.cpp

#include "tcpServer.h"TcpServer::TcpServer(QObject *parent) : QObject(parent)
{ser = new QTcpServer;ser->listen(QHostAddress::AnyIPv4, 8888);  //监听端口connect(ser, SIGNAL(newConnection()), this, SLOT(newConnected()));  //当新客户端来了与槽函数newConnected挂接上ser->waitForNewConnection(); //开启监听}

 main.cpp

#include <QCoreApplication>
#include "tcpserver.h"
int main(int argc, char *argv[])
{QCoreApplication a(argc, argv);TcpServer server;return a.exec();
}

这篇关于QT 网络编程 8的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/770296

相关文章

Qt实现对Word网页的读取功能

《Qt实现对Word网页的读取功能》文章介绍了几种在Qt中实现Word文档(.docx/.doc)读写功能的方法,包括基于QAxObject的COM接口调用、DOCX模板替换及跨平台解决方案,重点讨论... 目录1. 核心实现方式2. 基于QAxObject的COM接口调用(Windows专用)2.1 环境

Android使用java实现网络连通性检查详解

《Android使用java实现网络连通性检查详解》这篇文章主要为大家详细介绍了Android使用java实现网络连通性检查的相关知识,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录NetCheck.Java(可直接拷贝)使用示例(Activity/Fragment 内)权限要求

Qt实现删除布局与布局切换功能

《Qt实现删除布局与布局切换功能》在Qt应用开发中,动态管理布局是一个常见需求,比如根据用户操作动态删除某个布局,或在不同布局间进行切换,本文将详细介绍如何实现这些功能,并通过完整示例展示具体操作,需... 目录一、Qt动态删除布局1. 布局删除的注意事项2. 动态删除布局的实现步骤示例:删除vboxLay

Java AOP面向切面编程的概念和实现方式

《JavaAOP面向切面编程的概念和实现方式》AOP是面向切面编程,通过动态代理将横切关注点(如日志、事务)与核心业务逻辑分离,提升代码复用性和可维护性,本文给大家介绍JavaAOP面向切面编程的概... 目录一、AOP 是什么?二、AOP 的核心概念与实现方式核心概念实现方式三、Spring AOP 的关

Python实现简单封装网络请求的示例详解

《Python实现简单封装网络请求的示例详解》这篇文章主要为大家详细介绍了Python实现简单封装网络请求的相关知识,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录安装依赖核心功能说明1. 类与方法概览2.NetHelper类初始化参数3.ApiResponse类属性与方法使用实

MySQL的JDBC编程详解

《MySQL的JDBC编程详解》:本文主要介绍MySQL的JDBC编程,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录前言一、前置知识1. 引入依赖2. 认识 url二、JDBC 操作流程1. JDBC 的写操作2. JDBC 的读操作总结前言本文介绍了mysq

QT Creator配置Kit的实现示例

《QTCreator配置Kit的实现示例》本文主要介绍了使用Qt5.12.12与VS2022时,因MSVC编译器版本不匹配及WindowsSDK缺失导致配置错误的问题解决,感兴趣的可以了解一下... 目录0、背景:qt5.12.12+vs2022一、症状:二、原因:(可以跳过,直奔后面的解决方法)三、解决方

Debian 13升级后网络转发等功能异常怎么办? 并非错误而是管理机制变更

《Debian13升级后网络转发等功能异常怎么办?并非错误而是管理机制变更》很多朋友反馈,更新到Debian13后网络转发等功能异常,这并非BUG而是Debian13Trixie调整... 日前 Debian 13 Trixie 发布后已经有众多网友升级到新版本,只不过升级后发现某些功能存在异常,例如网络转

Python异步编程之await与asyncio基本用法详解

《Python异步编程之await与asyncio基本用法详解》在Python中,await和asyncio是异步编程的核心工具,用于高效处理I/O密集型任务(如网络请求、文件读写、数据库操作等),接... 目录一、核心概念二、使用场景三、基本用法1. 定义协程2. 运行协程3. 并发执行多个任务四、关键

AOP编程的基本概念与idea编辑器的配合体验过程

《AOP编程的基本概念与idea编辑器的配合体验过程》文章简要介绍了AOP基础概念,包括Before/Around通知、PointCut切入点、Advice通知体、JoinPoint连接点等,说明它们... 目录BeforeAroundAdvise — 通知PointCut — 切入点Acpect — 切面