服务端开发

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

服务端开发

本节内容介绍 QVSOA 服务端使用 Datagram 的方法。

开发须知

QVSOA 使用 QVsoaCliHandle::sendDatagram 方法发送数据包。

开发示例

下面以将来自客户端的数据原样发回为例,介绍使用 Datagram 开发 VSOA 服务端的方法。

#include <QCoreApplication>
#include <QDebug>
#include <QProcessEnvironment>
#include <QTimer>
#include <QVsoa>

constexpr char SERVER_INFO[] = "{\"name\":\"axis_server\"}";
constexpr char SERVER_ADDR[] = "0.0.0.0";
constexpr int SERVER_PORT = 3012;

int roll = 1;
int pitch = 1;
int yaw = 1;

void sendDatagram(QPointer<QVsoaCliHandle> client)
{
    client->sendDatagram(
        "/axis",
        QVsoaPayload(QString::asprintf("{\"roll\": %d, \"pitch\": %d, \"yaw\": %d}", roll++, pitch++, yaw++), {}));
}

void onNewClient(QPointer<QVsoaCliHandle> client)
{
    qDebug() << QStringLiteral("New client, address: %1:%2").arg(client->address().ip()).arg(client->address().port());
    auto timer = new QTimer;
    QObject::connect(timer, &QTimer::timeout, std::bind(sendDatagram, client));
    QObject::connect(client, &QVsoaCliHandle::destroyed, timer, &QTimer::deleteLater);
    timer->start(1000);
}

void onDisconnected(QPointer<QVsoaCliHandle> client)
{
    qDebug() << QStringLiteral("Client disconnect: %1:%2").arg(client->address().ip()).arg(client->address().port());
}

void onDatagram(QPointer<QVsoaCliHandle>, QString url, QVsoaPayload payload)
{
    qDebug() << "Datagram echo received from URL" << url << "with payload:" << payload.param();
}

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

    // Initialize server
    QVsoaServer server(SERVER_INFO);
    if (server.isInvalid()) {
        qDebug() << "Can not create VSOA server!";
        return -1;
    }

    QObject::connect(&server, &QVsoaServer::newClient, onNewClient);
    QObject::connect(&server, &QVsoaServer::clientDisconnect, onDisconnected);
    QObject::connect(&server, &QVsoaServer::datagram, onDatagram);

    int port = SERVER_PORT;
    int auto_port = QProcessEnvironment::systemEnvironment().value("VSOA_AUTO_PORT", "-1").toInt();
    if (auto_port != -1) {
        port = auto_port;
    }
    // Start server
    if (!server.start(QVsoaSocketAddress(AF_INET, SERVER_ADDR, port))) {
        qDebug() << "Can not start VSOA server!";
        return -1;
    }
    qDebug() << "Started VSOA server.";
    return a.exec();
}
文档内容是否对您有所帮助?
有帮助
没帮助