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

相关文章

Python中logging模块用法示例总结

《Python中logging模块用法示例总结》在Python中logging模块是一个强大的日志记录工具,它允许用户将程序运行期间产生的日志信息输出到控制台或者写入到文件中,:本文主要介绍Pyt... 目录前言一. 基本使用1. 五种日志等级2.  设置报告等级3. 自定义格式4. C语言风格的格式化方法

Spring 中的切面与事务结合使用完整示例

《Spring中的切面与事务结合使用完整示例》本文给大家介绍Spring中的切面与事务结合使用完整示例,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考... 目录 一、前置知识:Spring AOP 与 事务的关系 事务本质上就是一个“切面”二、核心组件三、完

sky-take-out项目中Redis的使用示例详解

《sky-take-out项目中Redis的使用示例详解》SpringCache是Spring的缓存抽象层,通过注解简化缓存管理,支持Redis等提供者,适用于方法结果缓存、更新和删除操作,但无法实现... 目录Spring Cache主要特性核心注解1.@Cacheable2.@CachePut3.@Ca

QT Creator配置Kit的实现示例

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

MySQL中On duplicate key update的实现示例

《MySQL中Onduplicatekeyupdate的实现示例》ONDUPLICATEKEYUPDATE是一种MySQL的语法,它在插入新数据时,如果遇到唯一键冲突,则会执行更新操作,而不是抛... 目录1/ ON DUPLICATE KEY UPDATE的简介2/ ON DUPLICATE KEY UP

Python中Json和其他类型相互转换的实现示例

《Python中Json和其他类型相互转换的实现示例》本文介绍了在Python中使用json模块实现json数据与dict、object之间的高效转换,包括loads(),load(),dumps()... 项目中经常会用到json格式转为object对象、dict字典格式等。在此做个记录,方便后续用到该方

MySQL分库分表的实践示例

《MySQL分库分表的实践示例》MySQL分库分表适用于数据量大或并发压力高的场景,核心技术包括水平/垂直分片和分库,需应对分布式事务、跨库查询等挑战,通过中间件和解决方案实现,最佳实践为合理策略、备... 目录一、分库分表的触发条件1.1 数据量阈值1.2 并发压力二、分库分表的核心技术模块2.1 水平分

SpringBoot请求参数传递与接收示例详解

《SpringBoot请求参数传递与接收示例详解》本文给大家介绍SpringBoot请求参数传递与接收示例详解,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋... 目录I. 基础参数传递i.查询参数(Query Parameters)ii.路径参数(Path Va

RabbitMQ 延时队列插件安装与使用示例详解(基于 Delayed Message Plugin)

《RabbitMQ延时队列插件安装与使用示例详解(基于DelayedMessagePlugin)》本文详解RabbitMQ通过安装rabbitmq_delayed_message_exchan... 目录 一、什么是 RabbitMQ 延时队列? 二、安装前准备✅ RabbitMQ 环境要求 三、安装延时队

Redis实现高效内存管理的示例代码

《Redis实现高效内存管理的示例代码》Redis内存管理是其核心功能之一,为了高效地利用内存,Redis采用了多种技术和策略,如优化的数据结构、内存分配策略、内存回收、数据压缩等,下面就来详细的介绍... 目录1. 内存分配策略jemalloc 的使用2. 数据压缩和编码ziplist示例代码3. 优化的