QT示例学习之QLocalSocket

2024-03-12 19:32
文章标签 学习 qt 示例 qlocalsocket

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

服务端头文件

#ifndef SERVER_H
#define SERVER_H#include <QWidget>
#include <QLabel>
#include <QPushButton>
#include <QLocalServer>class Server : public QWidget
{Q_OBJECTpublic:explicit Server(QWidget *parent = nullptr);private slots:void sendFortune();private:QLocalServer *server;QStringList fortunes;
};
#endif // SERVER_H

服务端实现文件

#include "server.h"
#include "ui_server.h"#include <QMessageBox>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QByteArray>
#include <QRandomGenerator>
#include <QLocalSocket>Server::Server(QWidget *parent): QWidget(parent)
{setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);server = new QLocalServer(this);if (!server->listen("fortune")) {QMessageBox::critical(this, tr("Local Fortune Server"),tr("Unable to start the server: %1").arg(server->errorString()));close();return ;}QLabel *statusLabel = new QLabel;statusLabel->setWordWrap(true);statusLabel->setText(tr("The server is running, Run the Local Fortune CLient example now."));fortunes << tr("You've been leading a dog's life. Stay off the furniture.")<< tr("You've got to think about tomorrow.")<< tr("You will be surprised by a loud noise.")<< tr("You will feel hungry again in another hour.")<< tr("You might have mail.")<< tr("You cannot kill time without injuring eternity.")<< tr("Computers are not intelligent. They only think they are.");QPushButton *quitButton = new QPushButton(tr("Quit"));quitButton->setAutoDefault(false);connect(quitButton, &QPushButton::clicked, this, &Server::close);connect(server, &QLocalServer::newConnection, this, &Server::sendFortune);QHBoxLayout *buttonLayout = new QHBoxLayout;buttonLayout->addStretch();buttonLayout->addWidget(quitButton);buttonLayout->addStretch();QVBoxLayout *mainLayout = new QVBoxLayout(this);mainLayout->addWidget(statusLabel);mainLayout->addLayout(buttonLayout);setWindowTitle(QGuiApplication::applicationDisplayName());
}void Server::sendFortune()
{QByteArray block;QDataStream out(&block, QIODevice::WriteOnly);out.setVersion(QDataStream::Qt_5_10);const int fortuneIndex = QRandomGenerator::global()->bounded(0, fortunes.size());const QString &message = fortunes.at(fortuneIndex);out << quint32(message.size());out << message;// 将下一个挂起的连接作为已连接的QLocalSocket对象返回QLocalSocket *clientConnection = server->nextPendingConnection();// 断开时删除对象connect(clientConnection, &QLocalSocket::disconnected, clientConnection, &QLocalSocket::deleteLater);// 将数据中最多maxSize字节的数据写入设备。返回实际写入的字节数,如果发生错误,则返回-1clientConnection->write(block);// 写入套接字clientConnection->flush();// 尝试关闭套接字clientConnection->disconnectFromServer();
}

 

 

客户端头文件

#ifndef CLIENT_H
#define CLIENT_H#include <QWidget>
#include <QLocalSocket>
#include <QDataStream>
#include <QLineEdit>
#include <QLabel>
#include <QPushButton>class Client : public QWidget
{Q_OBJECTpublic:explicit Client(QWidget *parent = nullptr);private slots:void requestNewFortune();void readFortune();void displayError(QLocalSocket::LocalSocketError socketError);void enableGetFortuneButton();private:QLineEdit *hostLineEdit;QPushButton *getFortuneButton;QLabel *statusLabel;QLocalSocket *socket;QDataStream in;quint32 blockSize;QString currentFortune;
};
#endif // CLIENT_H

 

 

客户端实现文件

#include "client.h"
#include "ui_client.h"#include <QDialogButtonBox>
#include <QGridLayout>
#include <QTimer>
#include <QMessageBox>Client::Client(QWidget *parent): QWidget(parent), hostLineEdit(new QLineEdit("fortune")), getFortuneButton(new QPushButton(tr("Get Fortune"))), statusLabel(new QLabel(tr("This examples requires that you run the Local Fortune Server example as well"))), socket(new QLocalSocket(this))
{setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);QLabel *hostLabel = new QLabel(tr("&Server name: "));hostLabel->setBuddy(hostLineEdit);statusLabel->setWordWrap(true);getFortuneButton->setDefault(true);QPushButton *quitButton = new QPushButton(tr("Quit"));QDialogButtonBox *buttonBox = new QDialogButtonBox;buttonBox->addButton(getFortuneButton, QDialogButtonBox::ActionRole);buttonBox->addButton(quitButton, QDialogButtonBox::RejectRole);in.setDevice(socket);in.setVersion(QDataStream::Qt_5_10);connect(hostLineEdit, &QLineEdit::textChanged, this, &Client::enableGetFortuneButton);connect(getFortuneButton, &QPushButton::clicked, this, &Client::requestNewFortune);connect(quitButton, &QPushButton::clicked, this, &Client::close);connect(socket, &QLocalSocket::readyRead, this, &Client::readFortune);connect(socket, QOverload<QLocalSocket::LocalSocketError>::of(&QLocalSocket::error), this, &Client::displayError);QGridLayout *mainLayout = new QGridLayout(this);mainLayout->addWidget(hostLabel, 0, 0);mainLayout->addWidget(hostLineEdit, 0, 1);mainLayout->addWidget(statusLabel, 2, 0, 1, 2);mainLayout->addWidget(buttonBox, 3, 0, 1, 2);setWindowTitle(QGuiApplication::applicationDisplayName());hostLineEdit->setFocus();}void Client::requestNewFortune()
{getFortuneButton->setEnabled(false);blockSize = 0;// 中止当前连接并重置套接字socket->abort();// 尝试与server建立连接socket->connectToServer(hostLineEdit->text());
}void Client::readFortune()
{if (blockSize == 0) {if (socket->bytesAvailable() < (int)sizeof (quint32)) {return ;}in >> blockSize;}if (socket->bytesToWrite() > blockSize || in.atEnd()) {return ;}QString nextFortune;in >> nextFortune;if (nextFortune == currentFortune) {QTimer::singleShot(0, this, &Client::requestNewFortune);return ;}currentFortune = nextFortune;statusLabel->setText(currentFortune);getFortuneButton->setEnabled(true);
}void Client::displayError(QLocalSocket::LocalSocketError socketError)
{switch (socketError) {case QLocalSocket::ServerNotFoundError:QMessageBox::information(this, tr("Local Fortune Client"),tr("The host was not found, Please make sure that the server is running and that the server name is correct."));break;case QLocalSocket::ConnectionRefusedError:QMessageBox::information(this, tr("Local Fortune Client"),tr("The connection was refused by peer, Make sure the fortune server is running, and check that the server name is correct."));break;case QLocalSocket::PeerClosedError:break;default:QMessageBox::information(this, tr("Local Fortune Client"),tr("The following error occurred: %1.").arg(socket->errorString()));break;}getFortuneButton->setEnabled(true);
}void Client::enableGetFortuneButton()
{getFortuneButton->setEnabled(!hostLineEdit->text().isEmpty());
}

 

这篇关于QT示例学习之QLocalSocket的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



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

相关文章

MySQL 主从复制部署及验证(示例详解)

《MySQL主从复制部署及验证(示例详解)》本文介绍MySQL主从复制部署步骤及学校管理数据库创建脚本,包含表结构设计、示例数据插入和查询语句,用于验证主从同步功能,感兴趣的朋友一起看看吧... 目录mysql 主从复制部署指南部署步骤1.环境准备2. 主服务器配置3. 创建复制用户4. 获取主服务器状态5

Spring Boot中的路径变量示例详解

《SpringBoot中的路径变量示例详解》SpringBoot中PathVariable通过@PathVariable注解实现URL参数与方法参数绑定,支持多参数接收、类型转换、可选参数、默认值及... 目录一. 基本用法与参数映射1.路径定义2.参数绑定&nhttp://www.chinasem.cnbs

Spring StateMachine实现状态机使用示例详解

《SpringStateMachine实现状态机使用示例详解》本文介绍SpringStateMachine实现状态机的步骤,包括依赖导入、枚举定义、状态转移规则配置、上下文管理及服务调用示例,重点解... 目录什么是状态机使用示例什么是状态机状态机是计算机科学中的​​核心建模工具​​,用于描述对象在其生命

PostgreSQL中rank()窗口函数实用指南与示例

《PostgreSQL中rank()窗口函数实用指南与示例》在数据分析和数据库管理中,经常需要对数据进行排名操作,PostgreSQL提供了强大的窗口函数rank(),可以方便地对结果集中的行进行排名... 目录一、rank()函数简介二、基础示例:部门内员工薪资排名示例数据排名查询三、高级应用示例1. 每

使用Python删除Excel中的行列和单元格示例详解

《使用Python删除Excel中的行列和单元格示例详解》在处理Excel数据时,删除不需要的行、列或单元格是一项常见且必要的操作,本文将使用Python脚本实现对Excel表格的高效自动化处理,感兴... 目录开发环境准备使用 python 删除 Excphpel 表格中的行删除特定行删除空白行删除含指定

SpringBoot线程池配置使用示例详解

《SpringBoot线程池配置使用示例详解》SpringBoot集成@Async注解,支持线程池参数配置(核心数、队列容量、拒绝策略等)及生命周期管理,结合监控与任务装饰器,提升异步处理效率与系统... 目录一、核心特性二、添加依赖三、参数详解四、配置线程池五、应用实践代码说明拒绝策略(Rejected

SQL中如何添加数据(常见方法及示例)

《SQL中如何添加数据(常见方法及示例)》SQL全称为StructuredQueryLanguage,是一种用于管理关系数据库的标准编程语言,下面给大家介绍SQL中如何添加数据,感兴趣的朋友一起看看吧... 目录在mysql中,有多种方法可以添加数据。以下是一些常见的方法及其示例。1. 使用INSERT I

Qt使用QSqlDatabase连接MySQL实现增删改查功能

《Qt使用QSqlDatabase连接MySQL实现增删改查功能》这篇文章主要为大家详细介绍了Qt如何使用QSqlDatabase连接MySQL实现增删改查功能,文中的示例代码讲解详细,感兴趣的小伙伴... 目录一、创建数据表二、连接mysql数据库三、封装成一个完整的轻量级 ORM 风格类3.1 表结构

SpringBoot中SM2公钥加密、私钥解密的实现示例详解

《SpringBoot中SM2公钥加密、私钥解密的实现示例详解》本文介绍了如何在SpringBoot项目中实现SM2公钥加密和私钥解密的功能,通过使用Hutool库和BouncyCastle依赖,简化... 目录一、前言1、加密信息(示例)2、加密结果(示例)二、实现代码1、yml文件配置2、创建SM2工具

MySQL 定时新增分区的实现示例

《MySQL定时新增分区的实现示例》本文主要介绍了通过存储过程和定时任务实现MySQL分区的自动创建,解决大数据量下手动维护的繁琐问题,具有一定的参考价值,感兴趣的可以了解一下... mysql创建好分区之后,有时候会需要自动创建分区。比如,一些表数据量非常大,有些数据是热点数据,按照日期分区MululbU