客户端开发

更新时间:
2024-02-20
下载文档

客户端开发

本节介绍客户端使用 QVSOA Stream 的方法。

开发须知

QVSOA 服务端与客户端均使用 QVsoaStream::createStream 方法创建 Stream。 在服务端接收到客户端的 RPC 请求时,服务端先行创建 Stream 并返回 tunnel ID 给客户端,以供客户端连接。 客户端接收到服务端返回的 tunnel ID 后可创建 Stream 连接服务端。

开发示例

#include <QCoreApplication>
#include <QDebug>
#include <QVsoa>

using namespace std::placeholders;

class StreamClient : public QObject
{
    Q_OBJECT
public:
    StreamClient()
    {
        QObject::connect(&m_client, &QVsoaClient::connected, this, &StreamClient::onConnected);
        QObject::connect(&m_client, &QVsoaClient::disconnected, this, &StreamClient::onDisconnected);
    }

    void onConnected(bool ok, QString info)
    {
        if (!ok) {
            qDebug() << "Connected with server failed!";
            return;
        }
        qDebug() << "Connected with server:" << info;
        readCall();
    }

    void onDisconnected() { qDebug() << "Connection break"; }

    void readCall()
    {
        auto invoker = new QVsoaClientRPCInvoker(&m_client, "/read", RPCMethod::GET);
        QObject::connect(invoker, &QVsoaClientRPCInvoker::serverReply, this, &StreamClient::onReadReplay);
        invoker->call(QVsoaPayload{});
    }

    void onReadReplay(const QVsoaHeader header)
    {
        auto stream = QVsoaStream::createStream(&m_client, header.tunid(), 1000, 5000);
        connect(stream, &QVsoaStream::connectionStatusChange, this, &StreamClient::onStreamConStatusChanged);
        connect(stream, &QVsoaStream::readyRead, this, &StreamClient::onStreamReadyRead);
        sender()->deleteLater();
    }

    void onStreamConStatusChanged(bool ok)
    {
        auto stream = qobject_cast<QVsoaStream*>(sender());
        if (!ok) {
            qDebug() << "Unable to connect to the server stream.";
            stream->deleteLater();
            return;
        }
        qDebug() << "Connected to VSOA stream server.";
    }

    void onStreamReadyRead()
    {
        auto stream = qobject_cast<QVsoaStream*>(sender());
        auto data = stream->readAll();
        qDebug() << "Received" << data.length() << "bytes from VSOA stream:" << data.toHex(':');
        stream->deleteLater();
    }

    void start()
    {
        if (m_client.isInvalid()) {
            qDebug() << "Can not create VSOA client!";
            return;
        }
        m_client.connect2server("vsoa://vsoa_stream_server", {});
    }

private:
    QVsoaClient m_client;
};

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    StreamClient client;
    client.start();

    return a.exec();
}

注意:
QVSOA 客户端可以与 C、JavaScript、Java 的 VSOA 服务端互联。

文档内容是否对您有所帮助?
有帮助
没帮助