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

相关文章

maven中的maven-antrun-plugin插件示例详解

《maven中的maven-antrun-plugin插件示例详解》maven-antrun-plugin是Maven生态中一个强大的工具,尤其适合需要复用Ant脚本或实现复杂构建逻辑的场景... 目录1. 核心功能2. 典型使用场景3. 配置示例4. 关键配置项5. 优缺点分析6. 最佳实践7. 常见问题

MySQL 添加索引5种方式示例详解(实用sql代码)

《MySQL添加索引5种方式示例详解(实用sql代码)》在MySQL数据库中添加索引可以帮助提高查询性能,尤其是在数据量大的表中,下面给大家分享MySQL添加索引5种方式示例详解(实用sql代码),... 在mysql数据库中添加索引可以帮助提高查询性能,尤其是在数据量大的表中。索引可以在创建表时定义,也可

Java集成Onlyoffice的示例代码及场景分析

《Java集成Onlyoffice的示例代码及场景分析》:本文主要介绍Java集成Onlyoffice的示例代码及场景分析,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要... 需求场景:实现文档的在线编辑,团队协作总结:两个接口 + 前端页面 + 配置项接口1:一个接口,将o

MySQL基本查询示例总结

《MySQL基本查询示例总结》:本文主要介绍MySQL基本查询示例总结,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录Create插入替换Retrieve(读取)select(确定列)where条件(确定行)null查询order by语句li

MybatisX快速生成增删改查的方法示例

《MybatisX快速生成增删改查的方法示例》MybatisX是基于IDEA的MyBatis/MyBatis-Plus开发插件,本文主要介绍了MybatisX快速生成增删改查的方法示例,文中通过示例代... 目录1 安装2 基本功能2.1 XML跳转2.2 代码生成2.2.1 生成.xml中的sql语句头2

MySQL数据库实现批量表分区完整示例

《MySQL数据库实现批量表分区完整示例》通俗地讲表分区是将一大表,根据条件分割成若干个小表,:本文主要介绍MySQL数据库实现批量表分区的相关资料,文中通过代码介绍的非常详细,需要的朋友可以参考... 目录一、表分区条件二、常规表和分区表的区别三、表分区的创建四、将既有表转换分区表脚本五、批量转换表为分区

PyTorch中cdist和sum函数使用示例详解

《PyTorch中cdist和sum函数使用示例详解》torch.cdist是PyTorch中用于计算**两个张量之间的成对距离(pairwisedistance)**的函数,常用于点云处理、图神经网... 目录基本语法输出示例1. 简单的 2D 欧几里得距离2. 批量形式(3D Tensor)3. 使用不

Python模拟串口通信的示例详解

《Python模拟串口通信的示例详解》pySerial是Python中用于操作串口的第三方模块,它支持Windows、Linux、OSX、BSD等多个平台,下面我们就来看看Python如何使用pySe... 目录1.win 下载虚www.chinasem.cn拟串口2、确定串口号3、配置串口4、串口通信示例5

C#使用MQTTnet实现服务端与客户端的通讯的示例

《C#使用MQTTnet实现服务端与客户端的通讯的示例》本文主要介绍了C#使用MQTTnet实现服务端与客户端的通讯的示例,包括协议特性、连接管理、QoS机制和安全策略,具有一定的参考价值,感兴趣的可... 目录一、MQTT 协议简介二、MQTT 协议核心特性三、MQTTNET 库的核心功能四、服务端(BR

SQL Server身份验证模式步骤和示例代码

《SQLServer身份验证模式步骤和示例代码》SQLServer是一个广泛使用的关系数据库管理系统,通常使用两种身份验证模式:Windows身份验证和SQLServer身份验证,本文将详细介绍身份... 目录身份验证方式的概念更改身份验证方式的步骤方法一:使用SQL Server Management S