QT示例学习之QLocalSocket

14 篇文章 0 订阅

服务端头文件

#ifndef SERVER_H
#define SERVER_H

#include <QWidget>
#include <QLabel>
#include <QPushButton>
#include <QLocalServer>

class Server : public QWidget
{
    Q_OBJECT

public:
    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字节的数据写入设备。返回实际写入的字节数,如果发生错误,则返回-1
    clientConnection->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_OBJECT

public:
    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());
}

 

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值