Overview
VSOA is the abbreviation of Vehicle SOA, VSOA provides a reliable, Real-Time SOA (Service Oriented Architecture) framework, this framework has multi-language and multi-environment implementation, developers can use this framework to build a distributed service model.
VSOA includes the following features:
- Support resource tagging of unified URL
- Support URL matching subscribe and publish model
- Support Real-Time Remote Procedure Call
- Support parallel multiple command sequences
- Support reliable and unreliable data publishing.
- Support multi-channel full-duplex high speed parallel data stream
- Support network QoS control
- Easily implement server fault-tolerant design
- Supports multiple language bindings
- Support middleware model
The user includes all qtvsoa features with the following code.
# app.pro
# In the project file of the qmake project, import the VSOA module using the following statement.
QT += vsoa
// app.cpp
// You can use this header to include all QVSOA features
#include <QVsoa>
Support
All available QVSOA class are shown below.
Class name | Describe |
---|---|
QVsoaSocketAddress | QVSOA socket address |
QVsoaServer | Provides the QVSOA server API |
QVsoaRPCServerListener | RPC listener used by the QVSOA server |
QVsoaCliHandle | Client connection handle used by the QVSOA server |
QVsoaClient | Provides the QVSOA client API |
QVsoaClientRPCInvoker | Asynchronous RPC invokeron for the QVSOA client |
QVsoaClientSynchronizer | Synchronous RPC invokeron for the QVSOA client |
QVsoaPayload | The payload used by QVSOA |
QVsoaHeader | The data header used by QVSOA |
QVsoaStream | Stream for transferring large files |
QVsoaPosition | QVSOA Position service |
QVsoaMiddleware | QVSOA Server middleware |
IQVsoaMiddlewareListener | Middleware uses a listener base class |
QVsoaMiddlewareResolve | The Middleware resolve data |
QVsoaRegulator | Regulator class |
QVSOA also provides good support for multi-thread, which can be implemented using any form of Qt code.
QVsoaSocketAddress Class
Represents a host address in QVSOA. There is no extra cost for copying this class, and the user does not need to care about the copy cost.
Methods
Method name | Describe |
---|---|
domain | Domain to which the socket belongs |
socketAddress | Get the sockaddr object |
addrSize | Get the size of the sockAddr object |
ip | Obtaining an IP Address |
port | Obtaining the Port Number |
security | Get security options |
isInvalid | Check the validity of the address |
QVsoaSocketAddress(const sockaddr *addr, socklen_t addrSize, bool sec = false)
QVsoaSocketAddress(int domain, const char *ip, uint16_t port, bool sec = false)
Constructor.
addr
Native sockaddr objects, optionally sockaddr_in and sockaddr_in6.addrSize
The size of theaddr
objectdomain
Socket domain, AF_INET and AF_INET6 are optional.ip
IP.port
Port.sec
Security options.
int QVsoaSocketAddress::domain() const
Domain to which the socket belongs.
Returns
Domain to which the socket belongs. The value can be AF_INET or AF_INET6.
const sockaddr *QVsoaSocketAddress::socketAddress() const
Get the sockaddr object.
Returns
Sockaddr object.
socklen_t QVsoaSocketAddress::addrSize() const
Get the size of the sockAddr object.
Returns
Sockaddr Specifies the size of the object.
QString QVsoaSocketAddress::ip() const
Obtaining an IP Address.
Returns
IP.
uint16_t QVsoaSocketAddress::port() const
Obtaining the Port Number.
Returns
Port.
bool QVsoaSocketAddress::security() const
Get security options.
Returns
Security options.
bool QVsoaSocketAddress::isInvalid()
Check the validity of the address.
Returns
Whether the address is invalid.
Examples
// main.cpp
#include <QCoreApplication>
#include <QDebug>
#include <QVsoa>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
// protocol: IPV4
// ip : 127.0.0.1
// port : 8080
QVsoaSocketAddress addr(AF_INET, "127.0.0.1", 8080)
qDebug() << "ip:" << addr.ip();
qDebug() << "port:" << addr.port();
return a.exec();
}
QVsoaServer Class
Vsoa server, It can be used to publish data, accept RPC requests, and other operations.
Methods
Method name | Describe | signal |
---|---|---|
isInvalid | Get the state of the object | |
native | Gets the native vsoa_server_t object | |
close | Shut down the server | |
setPassword | Set the password for connecting to the server | |
setSendTimeout | Set the global clients sending timeout of this server | |
bindIf | Set server binding network interface | |
start | Start the server at the specified address | |
count | Gets the number of clients connected to this server | |
clients | Gets all client connections to the server | |
client | Get client connections to the server | |
publish | Publish a message to the specified URL | |
isSubscribed | Whether any client has subscribed to the message at this URL | |
addMiddleware | Add Middleware to the server | |
addMiddlewareListener | Add Middleware listener to the server | |
clientConnectChanged | Client connection status changed | ● |
newClient | New client is connected | ● |
clientDisconnect | Client is disconnected | ● |
datagram | Receive a datagram | ● |
QVsoaServer::QVsoaServer(const QString &info, QObject *parent = nullptr)
Constructor.
info
Description of the server. This information can be obtained by the client.
bool QVsoaServer::isInvalid()
Get the state of the object.
Returns
Returnfalse
if the object is available,true
otherwise.
vsoa_server_t *QVsoaServer::native()
Gets the native vsoa_server_t object.
Returns
Native vsoa_server_t object.
void QVsoaServer::close()
Shut down the server.
bool QVsoaServer::setPassword(const QString &passwd)
Set the password for connecting to the server. This password is required when the client connects to the server.
passwd
Password.Returns
Success or failed.
bool QVsoaServer::setSendTimeout(bool curClis, int timeoutMs = -1)
Set the global clients sending timeout of this server, which defaults to 100 ms.
curClis
Whether to set the currently connected client at the same time.timeout
The global timeout period.Returns
Success or failed.
bool QVsoaServer::bindIf(const QString &ifname)
Set server binding network interface. Bind the server to the specified network interface, which can be called before start or after start.
ifname
Network interface.Returns
Success or failed.
bool QVsoaServer::start(const QVsoaSocketAddress &addr)
Start the server at the specified address.
addr
The server will start at this address.Returns
Success or failed.
int QVsoaServer::count()
Gets the number of clients connected to this server.
Returns
Number of Clients.
QList<QPointer<QVsoaCliHandle>> clients()
Gets all client connections to the server.
Returns
All client connection handles.
QPointer<QVsoaCliHandle> QVsoaServer::client(vsoa_cli_id_t id)
Get client connections to the server.
id
: Client IDReturns
: Client connection.
bool QVsoaServer::publish(const QString &url, const QVsoaPayload &payload, bool quick = false)
Publish a message to the specified URL, and all clients subscribed to the URL will receive the message.
url
The URL information.payload
Payload.quick
Whether to use the fast publication channel. By default, it is not used.Returns
Success or failed.
bool QVsoaServer::isSubscribed(const QString &url)
Whether any client has subscribed to the message at this URL. In general, if no client has subscribed to the URL, we do not need to publish the message.
url
The URL information.Returns
Return True if any client subscribed to the URL, false otherwise.
bool QVsoaServer::addMiddleware(const QString &url, const QVsoaMiddleware* mware)
Add middleware for handling RPC.
url
The URL information.mware
Middleware to be added.Returns
Success or failed.
QVsoaMiddleware *QVsoaServer::addMiddlewareListener(const QString &url, const QList<IQVsoaMiddlewareListener *> &listeners)
Add Middleware listener to handle RPC requests at the specified URL.
url
The URL information.listeners
All listeners to be added.Returns
Success or failed.
signal void QVsoaServer::clientConnectChanged(QPointer<QVsoaCliHandle> client, bool ok)
This signal is emitted when the connection status of the client is changed.
client
A client that connects to this server.ok
True if the connection is established, False if the connection is disconnected.
signal void QVsoaServer::newClient(QPointer<QVsoaCliHandle> client)
This signal is emitted when a new client establishes a connection.
client
A client that connects to this server.
signal void QVsoaServer::clientDisconnect(QPointer<QVsoaCliHandle> client)
This signal is emitted when the client is disconnected.
client
Disconnected clients.
signal void QVsoaServer::datagram(QPointer<QVsoaCliHandle> client, QString url, QVsoaPayload payload, bool quick)
This signal is emitted when a Datagram from the client is received.
client
The client that emits the Datagram.url
The URL information.payload
Payload.quick
Whether the fast send channel is used.
Examples
Start a simple VSOA server
// main.cpp
#include <QCoreApplication>
#include <QDebug>
#include <QVsoa>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QVsoaServer server("Test server");
QObject::connect(&server, &QVsoaServer::newClient, &server, [&](QPointer<QVsoaCliHandle> cli) {
qDebug() << "New client connected, IP:" << cli->address().ip();
});
server.setPassword("123456");
if (!server.start(QVsoaSocketAddress(AF_INET, "127.0.0.1", 8080))) {
qDebug() << "Start failed!";
}
return a.exec();
}
Send datagram
// main.cpp
#include <QCoreApplication>
#include <QDebug>
#include <QTimer>
#include <QVsoa>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QVsoaServer server("Test server");
QObject::connect(&server, &QVsoaServer::newClient, &server, [&](QPointer<QVsoaCliHandle> cli) {
qDebug() << "New client connected, IP:" << cli->address().ip();
});
// Publish datagrams to each client that connects to this server
QObject::connect(&server, &QVsoaServer::newClient, [](QPointer<QVsoaCliHandle> cli) {
QTimer *timer = new QTimer;
QObject::connect(timer, &QTimer::timeout, [=] {
if (cli) {
if (!cli->sendDatagram("/test", QVsoaPayload("Test param", {}))) {
qDebug() << "Send datagram failed";
}
} else {
timer->deleteLater();
}
});
timer->start(1000);
});
server.setPassword("123456");
if (!server.start(QVsoaSocketAddress(AF_INET, "127.0.0.1", 8080))) {
qDebug() << "Start failed!";
}
return a.exec();
}
Publish message
// main.cpp
#include <QCoreApplication>
#include <QDebug>
#include <QTimer>
#include <QVsoa>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QVsoaServer server("Test server");
QObject::connect(&server, &QVsoaServer::newClient, &server, [&](QPointer<QVsoaCliHandle> cli) {
qDebug() << "New client connected, IP:" << cli->address().ip();
});
server.setPassword("123456");
if (!server.start(QVsoaSocketAddress(AF_INET, "127.0.0.1", 8080))) {
qDebug() << "Start failed!";
return 1;
}
// publish message
QTimer *timer = new QTimer;
QVsoaPayload payload("test param", {});
QObject::connect(timer, &QTimer::timeout, [&] {
// If no client subscribes to this message, it does not need to be sent
if (!server.isSubscribed("/test")) {
qDebug() << "No client has subscribed to this message.";
return;
}
if (!server.publish("/test", payload)) {
qDebug() << "Publish failed!";
} else {
qDebug() << "Publish successed!";
}
});
timer->start(1000);
return a.exec();
}
QVsoaRPCServerListener Class
RPC listener for the VSOA Server.
Methods
Method name | Describe | signal |
---|---|---|
listen | Starts listening on the specified server | |
rmListen | Remove the listener on the specified server | |
setRPCHandler | Set up the RPC request handler function | |
RPCCall | An RPC request from a client | ● |
Type
Type name | Describe |
---|---|
RPCHandler | The type of function used to handle RPC requests |
QVsoaRPCServerListener::QVsoaRPCServerListener(const QString &url, QObject *parent = nullptr)
QVsoaRPCServerListener::QVsoaRPCServerListener(const QString &url, const RPCHandler &rpcHandler, QObject *parent)
Constructor.
url
The URL information to listen on.rpcHandler
RPC request handler function.
bool QVsoaRPCServerListener::listen(QVsoaServer *server)
Starts listening on the specified server.
server
Initiate a listener on this server.Returns
Success or failed.
void QVsoaRPCServerListener::rmListen(QVsoaServer *server)
Remove the listener on the specified server.
server
Server on which you want to remove listener.
void QVsoaRPCServerListener::setRPCHandler(const RPCHandler &onRPC)
Set up the RPC request handler function.
onRPC
RPC handler functions.
signal void QVsoaRPCServerListener::RPCCall(QPointer<QVsoaCliHandle> client, QVsoaHeader header, QString url, QVsoaPayload payload)
This signal is emitted when a client initiates an RPC request.
client
The client object that initiates the request.header
The data header of the VSOA.url
The URL information.payload
Payload.
using RPCHandler = std::function<void(QPointer<QVsoaCliHandle> client, const QVsoaHeader &header, const QString &url, const QVsoaPayload &payload)>
The function type of the RPC handler function.
client
The client object that initiates the request.header
The data header of the VSOA.url
The URL information.payload
Payload.
Examples
// main.cpp
#include <QCoreApplication>
#include <QDebug>
#include <QVsoa>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QVsoaServer server("Test server");
QObject::connect(&server, &QVsoaServer::newClient, &server, [&](QPointer<QVsoaCliHandle> cli) {
qDebug() << "New client connected, IP:" << cli->address().ip();
});
server.setPassword("123456");
if (!server.start(QVsoaSocketAddress(AF_INET, "127.0.0.1", 8080))) {
qDebug() << "Start failed!";
}
// Listen for rpc requests at url "/test".
QVsoaRPCServerListener testListen("/test");
testListen.listen(&server);
QObject::connect(&testListen,
&QVsoaRPCServerListener::RPCCall,
[](QPointer<QVsoaCliHandle> cli, QVsoaHeader header, QString url, QVsoaPayload payload) {
if (!cli) {
return;
}
qDebug() << "RPC The URL information:" << url;
qDebug() << "Param:" << payload.param();
// Respond to the rpc request.
// For details about QVsoaCliHandle, see the section "QVsoaCliHandle Class"
cli->reply(StatusCode::SUCCESS, header.seqno(), payload);
});
return a.exec();
}
QVsoaCliHandle Class
The client that connects to the server. This object should not be created by the user; it should be created by the server at the appropriate time.
Methods
Method name | Describe |
---|---|
id | Get client ID |
setAutoDelete | Enable or disable automatic deletion |
autoDelete | Whether to delete automatically or not |
sendDatagram | Send a Datagram |
reply | Reply the client's RPC request |
setKeepAlive | Set the keepalive option |
setPriority | The setting has a priority |
setTimeout | Set the client packet sending timeout |
setLingerTime | Set client socket linger time |
isSubscribed | Get whether the client is subscribed to the specified topic |
close | Close the connection to the client |
setAuthed | Set client authorization status |
authed | Get client authorization status. |
server | Gets the server object |
address | Get the address of the client |
vsoa_cli_id_t QVsoaCliHandle::id()
Get client ID.
Returns
Client ID.
bool QVsoaCliHandle::sendDatagram(const QString &url, const QVsoaPayload &payload, bool quick = false)
Send a Datagram.
url
The URL information.payload
Payload.quick
Whether to use the fast send channel. By default, the fast send channel is not used.Returns
Success or failed.
bool QVsoaCliHandle::reply(int status, int seqno, const QVsoaPayload &payload, int tunid = 0)
Reply the client's RPC request.
status
Processing status of the server.seqno
Data header from the RPC request.payload
Payload.tunid
Tunnel stream id, If the server has a tunnel stream enabled, you need to use this parameter to tell the client ID.Returns
Success or failed.
bool QVsoaCliHandle::setKeepAlive(int keepAlive)
Set the keepalive option.
keepAlive
Keepalive options.Returns
Success or failed.
bool QVsoaCliHandle::setPriority(int prio)
The setting has a priority.
prio
New priorities.Returns
Success or failed.
bool QVsoaCliHandle::setTimeout(int timeoutMs = -1)
Set the client packet sending timeout.
timeoutMs
Set network send timeout(ms). If the value is less than 0, use server global send timeout setting.Returns
Success or failed.
bool QVsoaCliHandle::setLingerTime(int timeSec)
Set client socket linger time.
timeoutSec
Unit is seconds, when the time is 0 , it means that the close call will be closed immediately.Returns
true if success, false if the client not exist.
bool QVsoaCliHandle::isSubscribed(const QString &url)
Get whether the client is subscribed to the specified topic.
url
Specified topic URL.Returns
true for subscribed, false for unsubscribed.
void QVsoaCliHandle::close()
Close the connection to the client.
bool QVsoaCliHandle::setAuthed(bool authed)
VSOA server set client authorization status. Unauthorized clients cannot receive publish messages.
authed
Authorization status.Returns
Success or failed.
bool QVsoaCliHandle::authed()
VSOA server get client authorization status. Defaults to true for new clients authenticated by server password.
Returns
Authorization status.
QVsoaServer *QVsoaCliHandle::server()
Gets the server object.
Returns
Server object.
QVsoaSocketAddress QVsoaCliHandle::address()
Get the address of the client.
Returns
Address.
QVsoaMiddleware Class
Middleware used on the server.
Methods
Method name | Describe |
---|---|
native | Get the vsoa_mware_t object |
isInvalid | Get the state of the object |
addListener | Add a new listener |
removeListener | Remove listener |
vsoa_mware_t *QVsoaMiddleware::native()
Get the vsoa_mware_t object.
Returns
The native vsoa_mware_t object held in QVsoaMiddleware.
bool QVsoaMiddleware::isInvalid()
Get the state of the object.
Returns
Returningtrue
if this object can be used,false
otherwise.
bool QVsoaMiddleware::addListener(const IQVsoaMiddlewareListener *listener)
Add a listener. When the RPC request arrives, the listener's hook function is called once until one of the hook functions returns false.
listener
Listeners to add.Returns
Success or failed.
void QVsoaMiddleware::removeListener(const IQVsoaMiddlewareListener *listener)
Remove listener.
listener
A listener to be removed.
Examples
// server mian.cpp
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QVsoaServer server("Test server");
QObject::connect(&server, &QVsoaServer::newClient, &server, [&](QPointer<QVsoaCliHandle> cli) {
qDebug() << "New client connected, IP:" << cli->address().ip();
});
server.setPassword("123456");
// Add middleware to the server
QVsoaMiddleware mware;
server.addMiddleware("/test", &mware);
// Add listener (For details about how to create a listener, see IQVsoaMiddlewareListener)
auto listener = new MyListener;
mware.addListener(listener);
auto listener2 = new MyListener2;
mware.addListener(listener2);
if (!server.start(QVsoaSocketAddress(AF_INET, "127.0.0.1", 8080))) {
qDebug() << "Start failed!";
}
return a.exec();
}
IQVsoaMiddlewareListener Interface
Middleware uses a listener base class.
Methods
Method name | Describe |
---|---|
hook | This method is called when the RPC request arrives |
virtual bool IQVsoaMiddlewareListener::hook(const QVsoaServer *server, QPointer<QVsoaCliHandle> client, const QVsoaHeader &header, const QString &url, const QVsoaPayload &payload, QVsoaMiddlewareResolve &resolve)
This method is implemented by the user. If true is returned, the hook continues, otherwise the chain ends.
server
Server object.client
Remote client connection.header
RPC request header.url
The URL of the RPC request.payload
The payload of RPC.resolve
Middleware Resolve Data.Returns
Returningtrue
will call the next hook method, and returningfalse
will end the call chain.
Examples
// server main.cpp
class MyListener : public IQVsoaMiddlewareListener
{
public:
bool hook(const QVsoaServer *server,
QPointer<QVsoaCliHandle> client,
const QVsoaHeader &header,
const QString &url,
const QVsoaPayload &payload,
QVsoaMiddlewareResolve &resolve) override
{
if (...) { /* when data not need passt to next hook */
/* do something */
client.reply(...); /* must reply to client */
return false;
} else {
/* do other thing */
return true; /* pass to next hook */
}
}
};
QVsoaMiddlewareResolve Class
The Middleware resolve data.
Methods
Method name | Describe |
---|---|
native | Get the vsoa_mware_resolve_t object |
addData | Add a new piece of data to Middleware resolve data. |
getData | Get a data. |
reply | Responding to rpc requests |
getMiddleware | Get Middleware object. |
Type
Type name | Describe |
---|---|
freeDataFun | A method used to release user data |
freeDataFunEx | A method used to release user data |
vsoa_mware_resolve_t *QVsoaMiddlewareResolve::native()
Get the native vsoa_mware_resolve_t object.
Returns
The native vsoa_mware_resolve_t object held in QVsoaMiddlewareResolve.
bool QVsoaMiddlewareResolve::addData(const QString &key, void *data, freeDataFun free = {})
bool QVsoaMiddlewareResolve::addData(const QString &key, void *data, freeDataFunEx freeFun = {})
bool QVsoaMiddlewareResolve::addData(const QString &key, void *data, ssize_t dataLen, freeDataFunEx freeFun = {})
Add a new piece of data to Middleware resolve data.
key
The Key used to index this data.data
Data to be added.dataLen
The resolve data buffer size. 0 means unknown.free
Use this method to release resources when this data is no longer needed. The method takes two parameters, the first being the data and the second being the key used to index the data.Returns
Returntrue
on success,false
otherwise.
void *QVsoaMiddlewareResolve::getData(const QString &key)
Get a data.
key
Index of data.Returns
Data.
bool QVsoaMiddlewareResolve::reply(uint8_t status, uint16_t tunid, const QVsoaPayload &payload)
Responding to rpc requests.
status
Response status.tunid
Used for stream transfer.payload
Payload to client.Returns
True if success, false if any errors.
QVsoaMiddleware *QVsoaMiddlewareResolve::getMiddleware()
Get Middleware object.
Returns
Middleware object.
using freeDataFun = std::function<void(void *data, const QString &Key)>
using freeDataFunEx = std::function<void(void *data, const QString &key, ssize_t value_len)>;
A method used to release user data.
data
Data to be released.key
Data index.valueLen
The length of data, 0 means unknown.
QVsoaClient Class
Vsoa client. You can subscribe to a message from the VSOA server or make an RPC request.
Methods
Method name | Describe | signal |
---|---|---|
isInvalid | Get the state of the object | |
native | Get the vsoa_client_t object | |
connect2server | Connect to the specified server | |
reconnect | Reconnect to the server | |
autoConnect | Enable automatic connection | |
stopAutoConnect | Stop automatic connection | |
isAutoConnect | Whether the client has auto-connect enabled | |
setKeepalive | Set the client Keepalive parameter | |
keepalive | Get the keepalive parameter of the client | |
disconnectServer | Disconnect from server | |
close | Close this client | |
isConnected | Whether the client is already connected to the server | |
setSendTimeout | Setting send timeout | |
setLingerTime | Set client socket linger time | |
ping | Ping the server to check whether the server connection is normal | |
stopPing | Stop ping | |
pingTurbo | VSOA client ping turbo | |
stopPingTurbo | Unset the ping turbo parameter | |
subscribe | Subscribe to the specified event (URL) | |
unsubscribe | Unsubscribe the specified event (URL) | |
unsubscribeAll | Unsubscribe from all events(URLS) | |
autoConsistent | VSOA client auto data consistent | |
addAutoConsistentURLs | Add urls of interest to the collection | |
removeAutoConsistentURLs | Remove urls of interest from the collection | |
setAutoConsistentRPCTimeout | Sets the RPC timeout for data consistency operations | |
setAutoConsistentURLs | Set the URL of interest | |
sendDatagram | Send datagram to server | |
connected | Client connect to the server | ● |
disconnected | Connection to the server is down | ● |
message | Message was received from the server | ● |
datagram | Datagram was received from the server | ● |
pingResponse | Ping operation gets a response | ● |
subscribeResult | Subscription request gets a response | ● |
unsubscribeResult | Unsubscription request gets a response | ● |
bool QVsoaClient::isInvalid()
Get the state of the object.
Returns
Returnfalse
if the object is available,true
otherwise.
vsoa_client_t *QVsoaClient::native()
Get the vsoa_client_t object.
Returns
The native vsoa_client_t object held in QVsoaClient.
void QVsoaClient::connect2server(const QVsoaSocketAddress &addr, const QString &passwd, int timeoutMs = -1)
void QVsoaClient::connect2server(const QString &server, const QString &passwd, int timeoutMs = -1)
Connect to the specified server.
addr
Server socket address.server
VSOA server, for example "vsoa://test_server".passwd
Server Connection Password.timeoutMs
Server connection timeout, unit of milliseconds. Less than 0 never times out.
void QVsoaClient::reconnect()
Reconnect to the server.
bool QVsoaClient::autoConnect(unsigned int reconnDelayMs = 0);
bool QVsoaClient::autoConnect(unsigned int connTimeoutMs, unsigned int reconnDelayMs);
The function of automatically connecting to the server is enabled. When a client cannot connect to the server or is disconnected from the server, it automatically attempts to reconnect to the server.
connTimeoutMs
Timeout in milliseconds for automatic connections.reconnDelayMs
Reconnection interval in milliseconds.Returns
Success or failed.
void QVsoaClient::stopAutoConnect();
The automatic connection function is disabled.
bool QVsoaClient::isAutoConnect() const
Whether the client has auto-connect enabled.
Returns
Returnstrue
if auto-connect is enabled,false
otherwise.
bool QVsoaClient::setKeepalive(unsigned int keepaliveMs)
Set the client Keepalive parameter. The client will continuously ping the server at keepaliveMs
intervals.
keepaliveMs
Elapsed time between pings, in milliseconds.Returns
It returnstrue
if the setting was successful andfalse
otherwise.
unsigned int QVsoaClient::keepalive() const
Get the keepalive parameter of the client.
Returns
Elapsed time between pings, in milliseconds.
bool QVsoaClient::disconnectServer()
Disconnect from server After disconnect, the connect2server function can be called again.
Returns
Success or failed.
void QVsoaClient::close()
Close this client.
bool QVsoaClient::isConnected()
Whether the client is already connected to the server.
Returns
Returns True if already connected, False otherwise.
bool QVsoaClient::setSendTimeout(int timeoutMs = -1)
Setting Send Timeout.
timeoutMs
Timeout, in milliseconds. If the value is less than 0, VSOA_CLIENT_DEF_SEND_TIMEOUT is used.Returns
Success or failed.
bool QVsoaClient::setLingerTime(int timeSec)
Set client socket linger time.
timeSec
Linger time in seconds.Returns
true if success, false if any errors.
void QVsoaClient::ping(int pingIntervalMs, int pingTimeoutMs = -1, int pingCount = -1)
Ping the server to check whether the server connection is normal.
pingIntervalMs
Ping interval time.pingTimeoutMs
Ping timeout period.pingCount
The number of pings, if it's less than 0, it keeps pinging.
void QVsoaClient::stopPing()
Stop ping.
bool QVsoaClient::pingTurbo(unsigned int turboMs, unsigned int maxCnt)
VSOA client ping turbo. When there is an RPC call pending, and if there is data packet loss,and the client and server need to do their best to perform TCP fast retransmission at this time, you can set this turboMs
parameter, the minimum value is 25ms. 0 means disable turbo ping. When turbo ping is enabled, the turboMs
value must be less than or equal to keepalive in setKeepalive()
turboMs
ping interval time.maxCnt
Maximum number of consecutive pings.Returns
It returns true if the setting was successful and false otherwise.
bool QVsoaClient::stopPingTurbo()
Unset the ping turbo parameter.
Returns
Returns true on success, false otherwise.
bool QVsoaClient::subscribe(const QString &url, int timeoutMs)
bool QVsoaClient::subscribe(const QStringList &urls, int timeoutMs)
Subscribe to the specified event (URL), When the server sends the corresponding event, the Client can receive the event. When the client reconnects with the server, it will automatically subscribe to all urls it has subscribed to so far.
url
Event that need to be subscribed.urls
Events that need to be subscribed.timeoutMs
Timeout, in milliseconds. Less than 0 never times out.Returns
Success or failed.
Note: The client will try to re-subscribe to the url when it reconnects, whether this method is called successfully or not.
bool QVsoaClient::unsubscribe(const QString &url, int timeoutMs = -1)
bool QVsoaClient::unsubscribe(const QStringList &urls, int timeoutMs = -1)
Unsubscribe the specified event. Unsubscribed urls will no longer be subscribed automatically when reconnecting.
url
Event that need to be unsubscribed.urls
Events that need to be unsubscribed.timeoutMs
Timeout, in milliseconds. Less than 0 never times out.Returns
If true on success, return False on any error.
Note: The client will no longer try to subscribe to the URLS when it reconnects, whether this method is called successfully or not.
bool QVsoaClient::unsubscribeAll(int timeoutMs)
Unsubscribe from all subscribed urls. When reconnecting, no urls will be automatically subscribed anymore.
timeoutMs
Timeout, in milliseconds. Less than 0 never times out.Returns
If true on success, return False on any error.
Note: The client will no longer try to subscribe to the URLS when it reconnects, whether this method is called successfully or not.
bool QVsoaClient::autoConsistent(const QStringList &urls, unsigned int rpcTimeoutMs)
VSOA client auto data consistent. When VSOA disconnected and reconnected, the server data changes, which we cannot detect, so this function can set the urls
collection of interest. When the client connection is successful, the data is automatically fetched using the RPC method with the GET parameter and a message signal is issued. The timeout for each RPC request will be set to rpcTimeoutMs
.
urls
urls of interest.rpcTimeoutMs
The timeout for rpc requests.Returns
true on success, false otherwise.
bool QVsoaClient::addAutoConsistentURLs(const QStringList &urls)
Add urls
to the collection to maintain data consistency.
urls
urls of interest.Returns
true on success, false otherwise.
bool QVsoaClient::removeAutoConsistentURLs(const QStringList &urls)
Remove the urls
of interest from the collection.
urls
Not interested urlsReturns
true on success, false otherwise.
bool QVsoaClient::setAutoConsistentRPCTimeout(unsigned int rpcTimeoutMs)
Set Auto consistent RPC request timeout to rpcTimeoutMs
.
rpcTimeoutMs
The timeout for rpc requests.Returns
true on success, false otherwise.
bool QVsoaClient::setAutoConsistentURLs(const QStringList &urls)
Sets the set of urls
that are of interest when dealing with data consistency.
urls
urls of interest.Returns
true on success, false otherwise.
bool QVsoaClient::sendDatagram(const QString &url, const QVsoaPayload &payload, bool quick = false)
Send datagram to server
url
URL.payload
The payload to be sent.quick
True if a quick publish channel is used, false otherwise.Returns
true on success, false otherwise.
signal void QVsoaClient::connected(bool ok, QString info)
This signal is emitted when a successful connection to the server or a timeout occurs.
ok
True if the connection to the server was successful, False otherwise.info
This parameter is the information returned by the server when the connection to the server is successful.
signal void QVsoaClient::disconnected()
This signal is emitted when the server is disconnected.
signal void QVsoaClient::message(QString url, QVsoaPayload payload, bool quick)
This signal is emitted when the server sends a message.
url
The URL information.payload
Payload.quick
True if a quick publish channel is used, false otherwise.
signal void QVsoaClient::datagram(QString url, QVsoaPayload payload, bool quick)
This signal is emitted when the server sends a Datagram.
url
The URL information.payload
Payload.quick
True if a quick channel is used, false otherwise.
signal void QVsoaClient::pingResponse(bool ok)
This signal is emitted when the ping is responded to.
ok
The value is true if the ping succeeds, false otherwise.
signal void QVsoaClient::subscribeResult(QStringList urls, bool ok)
This signal is emitted when a subscription request is processed.
urls
The URL information list.ok
Success or failed.
signal void QVsoaClient::unsubscribeResult(QStringList urls, bool ok)
This signal is emitted when an unsubscribe request is responded to.
urls
The URL information list.ok
Success or failed.
Examples
Ping
// main.cpp
#include <QCoreApplication>
#include <QDebug>
#include <QTimer>
#include <QVsoa>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QVsoaClient client;
QObject::connect(&client, &QVsoaClient::connected, &client, [&](bool success, QString info) {
if (!success) {
qDebug() << "Connecting to the server failed!";
return;
}
qDebug() << "Connecting to the server succeeded! Server info:" << info;
// Ping the server 10 times every 2 seconds. The timeout period is 1 second.
client.ping(2000, 1000, 10);
});
QObject::connect(&client, &QVsoaClient::pingResponse, [&](bool success) {
qDebug() << "Ping" << (success ? "successed" : "failed");
});
// Connect to the specified server.
client.connect2server(QVsoaSocketAddress(AF_INET, "127.0.0.1", 8080), "123456");
return a.exec();
}
Subscribed
// main.cpp
#include <QCoreApplication>
#include <QDebug>
#include <QVsoa>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QVsoaClient client;
QObject::connect(&client, &QVsoaClient::connected, [&](bool success, QString info) {
if (!success) {
qDebug() << "Connecting to the server failed!";
return;
}
qDebug() << "Connecting to the server succeeded! Server info:" << info;
// Subscribe to messages at url"/test".
if (!client.subscribe("/test", 0)) {
qDebug() << "Subscribe failed.";
}
});
QObject::connect(&client, &QVsoaClient::subscribeResult, [&](QStringList urls, bool success) {
if (success) {
qDebug() << "Subscribe successed.";
} else {
qDebug() << "Subscribe failed.";
}
qDebug() << "The URL information:" << urls;
});
// Process the message from the server.
QObject::connect(&client, &QVsoaClient::message, [](QString url, QVsoaPayload payload, bool quick) {
qDebug() << "The URL information:" << url;
qDebug() << "Param:" << payload.param();
qDebug() << "Quick:" << quick;
});
client.connect2server(QVsoaSocketAddress(AF_INET, "127.0.0.1", 8080), "123456");
return a.exec();
}
Datagram
// main.cpp
#include <QCoreApplication>
#include <QDebug>
#include <QVsoa>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QVsoaClient client;
QObject::connect(&client, &QVsoaClient::connected, &client, [&](bool success, QString info) {
if (!success) {
qDebug() << "Connecting to the server failed!";
return;
}
qDebug() << "Connecting to the server succeeded! Server info:" << info;
});
// Process datagrams from the server.
QObject::connect(&client, &QVsoaClient::datagram, &client, [&](QString url, QVsoaPayload payload, bool quick) {
qDebug() << "The URL information:" << url;
qDebug() << "Param:" << payload.param();
qDebug() << "Quick:" << quick;
});
client.connect2server(QVsoaSocketAddress(AF_INET, "127.0.0.1", 8080), "123456");
return a.exec();
}
QVsoaClientRPCInvoker Class
The client RPC invoker.
Methods
Method name | Describe | signal |
---|---|---|
call | Initiate a remote procedure call | |
client | Get the client object | |
url | Get the url | |
method | Get the RPC method | |
serverReply | Server responded to the RPC request | ● |
QVsoaClientRPCInvoker::QVsoaClientRPCInvoker(QVsoaClient *client, const QString &url, int method)
Constructor.
client
The client object that initiates the RPC.url
The URL information.method
RPC Call method, The options areRPCMethod::GET
orRPCMethod::SET
bool QVsoaClientRPCInvoker::call(const QVsoaPayload &payload, int timeoutMs = -1)
bool QVsoaClientRPCInvoker::call(const QVsoaPayload &payload, const QVariant &arg, int timeoutMs = -1)
Initiate a remote procedure call.
payload
Payload.arg
This parameter is sent with the serverReply signal when the rpc request is answered.timeoutMs
RPC timeout, if less than 0, never times out.Returns
Success or failed.
QVsoaClient *QVsoaClientRPCInvoker::client()
Get the client object.
Returns
Client object.
QString QVsoaClientRPCInvoker::url()
Get the url.
Returns
The URL information.
int QVsoaClientRPCInvoker::method()
Get the RPC method.
Returns
Method.
signal void QVsoaClientRPCInvoker::serverReply(const QVsoaHeader header, const QVsoaPayload payload)
This signal is emitted when the RPC gets a response from the server.
header
VSOA data header. When this object is invalid, the RPC request times out or fails.payload
Payload.
Examples
// main.cpp
#include <QCoreApplication>
#include <QDebug>
#include <QTimer>
#include <QVsoa>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QVsoaClient client;
QObject::connect(&client, &QVsoaClient::connected, &client, [&](bool success, QString info) {
if (!success) {
qDebug() << "Connecting to the server failed!";
return;
}
qDebug() << "Connecting to the server succeeded! Server info:" << info;
QTimer *timer = new QTimer;
// Construct an invoker.
QVsoaClientRPCInvoker *invoker = new QVsoaClientRPCInvoker(&client, "/test", RPCMethod::GET);
QObject::connect(invoker,
&QVsoaClientRPCInvoker::serverReply,
invoker,
[](QVsoaHeader header, QVsoaPayload payload) {
if (header.isInvalid()) {
qDebug() << "Call failed.";
}
qDebug() << "Param:" << payload.param();
});
// An RPC is initiated at an interval of 1 second.
QObject::connect(timer, &QTimer::timeout, [=] {
invoker->call(QVsoaPayload("test param", {}));
});
timer->start(1000);
});
client.connect2server(QVsoaSocketAddress(AF_INET, "127.0.0.1", 8080), "123456");
return a.exec();
}
QVsoaClientSynchronizer Class
The client's RPC synchronizer, which can be used to make synchronous RPC calls.
Methods
Method name | Describe |
---|---|
call | Initiate a remote procedure call |
close | Close the synchronizer |
QVsoaClientSynchronizer::QVsoaClientSynchronizer(QVsoaClient *parent, bool dynamic = false)
Constructor.
parent
The Client object on which we will initiate the synchronous RPC.dynamic
Ifdynamic
istrue
, it means that the package memory is dynamically applied for each time the call receives a reply from the server. When it isfalse
, it means that it is only applied statically once.
QPair<bool, QVsoaHeader> QVsoaClientSynchronizer::call(const QString &url, int method, const QVsoaPayload &payload, int timeoutMs)
This method is a blocking method, but internally maintains a Qt event loop to ensure that Qt events are not blocked, and returns when the call is complete.
url
The URL information.method
The value is the enumeration value of RPCMethod.payload
Payload.timeoutMs
Timeout, in milliseconds. If it is less than 0, it never times out.Returns
The first value indicates whether the call was successful, and the second value is the data header returned by RPC.
bool QVsoaClientSynchronizer::close()
Close the synchronizer.
Returns
Success or failed.
Examples
// main.cpp
#include <QCoreApplication>
#include <QDebug>
#include <QTimer>
#include <QVsoa>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QVsoaClient client;
QTimer *timer = new QTimer;
timer->start(1000);
QObject::connect(&client, &QVsoaClient::connected, &client, [&](bool success, QString info) {
if (!success) {
qDebug() << "Connecting to the server failed!";
return;
}
qDebug() << "Connecting to the server succeeded! Server info:" << info;
// Construct a synchronous caller.
QVsoaClientSynchronizer *sync = new QVsoaClientSynchronizer(&client);
// Synchronize RPC at an interval of 1 second.
// Note: Normal logic code should not do this.
// You need to avoid calling a synchronization request when a synchronization request is not completed.
QObject::connect(timer, &QTimer::timeout, [=] {
QPair<bool, QVsoaHeader> ret = sync->call("/test", RPCMethod::GET, QVsoaPayload("test param", {}));
if (ret.first) {
qDebug() << "Param:" << ret.second.payload().param();
}
});
});
client.connect2server(QVsoaSocketAddress(AF_INET, "127.0.0.1", 8080), "123456");
return a.exec();
}
QVsoaPayload Class
The payload in the VSOA. There is no extra cost for copying this class, and the user does not need to care about the copy cost.
Methods
Method name | Describe |
---|---|
hasParam | Payload Whether payload has param |
hasData | Payload Whether payload has data |
setParam | Set the param |
param | Get the param |
setData | Set the data |
data | Get the data |
QVsoaPayload::QVsoaPayload(const QString ¶m, const QByteArray &data, QObject *parent = nullptr)
Constructor.
param
Param.data
Data.
bool QVsoaPayload::hasParam() const
Payload Whether payload has param.
Returns
Returns True if param is present, false otherwise.
bool QVsoaPayload::hasData() const
Payload Whether payload has data.
Returns
Returns True if data is present, false otherwise.
void QVsoaPayload::setParam(const QString ¶m)
Set the param.
param
Param.
QString QVsoaPayload::param() const
Get the param.
Returns
Param.
void QVsoaPayload::setData(const QByteArray &data)
Set the data.
data
Data.
QByteArray QVsoaPayload::data() const
Get the data.
Returns
Data.
Examples
// main.cpp
#include <QCoreApplication>
#include <QDebug>
#include <QVsoa>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
// Construct a payload
QVsoaPayload payload("Test param", {});
if (payload.hasParam()) {
qDebug() << payload.param();
}
// We don't have data, so we're not going to print anything.
if (payload.hasData()) {
qDebug() << payload.data();
}
return a.exec();
}
QVsoaHeader Class
The data header of the VSOA. This object cannot be created by the user, the user can only use it. There is no extra cost for copying this class, and the user does not need to care about the copy cost.
Methods
Method name | Describe |
---|---|
url | Get the URL |
seqno | Get the seqno |
flags | Get the flags |
status | Get the status |
tunid | Get the tunid |
isInvalid | Whether the current object is valid |
QString QVsoaHeader::url() const
Get the URL.
Returns
The URL information.
uint32_t QVsoaHeader::seqno() const
Get the seqno.
Returns
Sequence number.
uint8_t QVsoaHeader::flags() const
Get the flags.
Returns
Flags.
uint8_t QVsoaHeader::status() const
Get the status.
Returns
Status.
uint16_t QVsoaHeader::tunid() const
Get the tunid.
Returns
Tunnel ID.
bool QVsoaHeader::isInvalid() const
Whether the current object is valid.
Returns
Returningtrue
if invalid,false
otherwise.
QVsoaStream Class
Vsoa Stream. Can be used for large file transfer.
Methods
Method name | Describe | signal |
---|---|---|
read | Read data from the stream | |
readAll | Read all data from the stream | |
write | Writes data to a stream | |
close | Closing the current Stream | |
tunid | Get the stream tunnel ID | |
isInvalid | Whether the current stream is invalid | |
readyRead | Stream can be read | ● |
connectionStatusChange | Stream connection status changed | ● |
connectTimeout | Connection timeout | ● |
Global method
Method name | Describe |
---|---|
createStream | Create a stream |
ssize_t QVsoaStream::read(void *buf, size_t bufSize)
Read data from the stream.
buf
Data buffer zone.bufSize
Buffer size.Returns
The number of bytes read successfully.
QByteArray QVsoaStream::read(ssize_t maxSize)
Read data from the stream.
maxSize
The amount of data you want to read.Returns
The data that was read.
QByteArray QVsoaStream::readAll()
Read all data from the stream.
Returns
The data that was read.
ssize_t QVsoaStream::write(const void *buf, size_t bufSize)
Writes data to a stream.
buf
Data buffer zone.bufSize
Buffer size.Returns
The number of bytes written successfully.
ssize_t QVsoaStream::write(const QByteArray &data)
Writes data to a stream.
data
Data to be written.Returns
The number of bytes written successfully.
void QVsoaStream::close()
Closing the current Stream.
int QVsoaStream::tunid()
Get the stream tunnel ID.
Returns
Tunnel ID.
bool QVsoaStream::isInvalid()
Whether the current stream is invalid.
Returns
Returningtrue
if invalid,false
otherwise.
signal void QVsoaStream::readyRead()
This signal is emitted when data is available to read.
signal void QVsoaStream::connectionStatusChange(bool ok)
This signal is emitted when the connection status changes.
ok
If true, the connection is successfully established; otherwise, the connection is disconnected.
signal void QVsoaStream::connectTimeout()
This signal is emitted when the connection times out.
QVsoaStream *createStream(QVsoaServer *server, int keepalive, int timeoutMs = -1)
QVsoaStream *createStream(QVsoaClient *client, int tunid, int keepalive, int timeoutMs = -1)
Creating a stream.
server
VSOA server object.client
VSOA client object.tunid
Stream tunnel ID.keepalive
Keepalive.timeoutMs
Timeout, if less than 0, then never timeout.Returns
Stream object.
Examples
// server.cpp
#include <QCoreApplication>
#include <QDebug>
#include <QTimer>
#include <QVsoa>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QVsoaServer server("Test server");
QObject::connect(&server, &QVsoaServer::newClient, &server, [&](QPointer<QVsoaCliHandle> cli) {
qDebug() << "New client connected, IP:" << cli->address().ip();
});
server.setPassword("123456");
if (!server.start(QVsoaSocketAddress(AF_INET, "127.0.0.1", 8080))) {
qDebug() << "Start failed!";
}
// Upon receiving this rpc request,
// We create a stream and notify the client to connect to this stream.
QVsoaRPCServerListener createStreamListeen("/stream");
createStreamListeen.listen(&server);
QObject::connect(&createStreamListeen,
&QVsoaRPCServerListener::RPCCall,
[&](QPointer<QVsoaCliHandle> cli, QVsoaHeader header, QString, QVsoaPayload) {
qDebug() << "Create stream";
auto stream = createStream(&server, header.tunid(), 5000);
QObject::connect(stream, &QVsoaStream::connectionStatusChange, [=](bool link) {
if (link) {
qDebug() << "Stream connected.";
} else {
qDebug() << "Stream disconnected.";
stream->deleteLater();
}
});
// Tells the client stream's tunid
// that the client will use this ID to connect to the stream.
cli->reply(StatusCode::SUCCESS, header.seqno(), QVsoaPayload(), stream->tunid());
// Read data from stream.
QObject::connect(stream, &QVsoaStream::readyRead, [=] {
qDebug() << stream->readAll();
});
// Writes data to stream periodically.
QTimer *timer = new QTimer;
QObject::connect(timer, &QTimer::timeout, stream, [=] {
stream->write("Hello, this is test server.");
});
timer->start(1000);
});
return a.exec();
}
// client.cpp
#include <QCoreApplication>
#include <QDebug>
#include <QTimer>
#include <QVsoa>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QVsoaClient client;
QObject::connect(&client, &QVsoaClient::connected, [&](bool success, QString info) {
if (!success) {
qDebug() << "Connecting to the server failed!";
return;
}
qDebug() << "Connecting to the server succeeded! Server info:" << info;
QVsoaClientRPCInvoker *invoker = new QVsoaClientRPCInvoker(&client, "/stream", RPCMethod::GET);
// Request the server to start stream.
QObject::connect(invoker, &QVsoaClientRPCInvoker::serverReply, [&](QVsoaHeader header, QVsoaPayload payload) {
// Create a stream
auto stream = createStream(&client, header.tunid(), 5);
// Wait for the stream connection to succeed
QObject::connect(stream, &QVsoaStream::connectionStatusChange, [stream, &client](bool link) {
if (link) {
// Periodically writes data to stream
QTimer *timer = new QTimer;
qDebug() << "Stream connected.";
QObject::connect(timer, &QTimer::timeout, stream, [stream] {
stream->write(QByteArray("stream test data"));
});
timer->start(1000);
} else {
qDebug() << "Stream disconnected.";
stream->deleteLater();
}
});
// Process the data received from the stream
QObject::connect(stream, &QVsoaStream::readyRead, [stream] {
qDebug() << stream->readAll();
});
});
if (!invoker->call(QVsoaPayload())) {
qDebug() << "create stream failed.";
}
});
client.connect2server(QVsoaSocketAddress(AF_INET, "127.0.0.1", 8080), "123456");
return a.exec();
}
QVsoaPosition Class
Vsoa position. You can query the address of the server.
Methods
Method name | Describe |
---|---|
start | Starting the position service |
close | Closing the position service |
replay | Address to respond to the request |
isInvalid | Whether the current object is valid |
query | Address query method |
setPositionLookup | VSOA set position lookup |
lookup | Used to find the specified server address in the Position service |
QVsoaPosition::QVsoaPosition(const QMultiMap<QString, QVsoaSocketAddress> &map, QObject *parent = nullptr)
Constructor.
map
Server address mapping table.
bool QVsoaPosition::start(const QVsoaSocketAddress &addr)
Starting the position service.
addr
Launch position at this address.Returns
Success or failed.
void QVsoaPosition::close()
Closing the position service.
void QVsoaPosition::replay(vsoa_position_response_t *response, const QVsoaSocketAddress &addr)
Address to respond to the request.
response
Request object.addr
Address.
bool QVsoaPosition::isInvalid()
Whether the current object is valid.
Returns
Returntrue
if invalid,false
otherwise.
virtual QVsoaSocketAddress QVsoaPosition::query(int domain, const QString &query_name)
Address query method, which the user can override.
domain
Socket domain.query_name
Name of the server to be queried.Returns
Address.
static bool QVsoaPosition::setPositionLookup(const QVsoaSocketAddress &pos)
VSOA set position lookup.
pos
The specified position address.Returns
Success or failed.
static QVsoaSocketAddress QVsoaPosition::lookup(int domain, const QString &name, int timeoutMs = -1)
static QVsoaSocketAddress QVsoaPosition::lookup(const QVsoaSocketAddress &pos, int domain, const QString &name, int timeoutMs = -1)
Used to find the specified server address in the Position service. VSOA position lookup (Synchronous) domain == -1 means any socket family If position server is specified, only the specified server will be queried, If the position server address has not been specified, this function will first use the environment variable VSOA_POS_SERVER
to query, if not found, it will use the server query configured in /etc/vsoa.pos
.
domain
Domain where the server address resides.name
Name of the server.timeoutMs
Timeout. The timeout period, if less than 0, will never timeout.Returns
Address.
Examples
// stream.cpp
#include <QCoreApplication>
#include <QVsoa>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
// Record two IP addresses for the client to query.
QVsoaPosition position({
{"local", QVsoaSocketAddress(AF_INET, "127.0.0.1", 8081, false)},
{"local", QVsoaSocketAddress(AF_INET6, "0:0:0:0:0:0:0:1", 8081, true) }
});
// Starting the Position service.
position.start(QVsoaSocketAddress(AF_INET, "127.0.0.1", 8080));
return a.exec();
}
// client.cpp
#include <QCoreApplication>
#include <QDebug>
#include <QVsoa>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
// Quer server address.
QVsoaSocketAddress ipv4 = QVsoaPosition::lookup(QVsoaSocketAddress(AF_INET, "127.0.0.1", 8080), AF_INET, "local");
QVsoaSocketAddress ipv6 = QVsoaPosition::lookup(QVsoaSocketAddress(AF_INET, "127.0.0.1", 8080), AF_INET6, "local");
qDebug() << "IPV4 IP:" << ipv4.ip() << "Port:" << ipv4.port() << "Security" << ipv4.security();
qDebug() << "IPV6 IP:" << ipv6.ip() << "Port:" << ipv6.port() << "Security" << ipv6.security();
return a.exec();
}
QVsoaRegulator Class
Regulator can be used to regulate the publish frequency and the monitoring frequency.
Methods
Method name | Describe |
---|---|
native | Gets the vsoa_regulator_t object of the Regulator |
setRegulatorPeriod | Set Regulator Period |
addSlot | Add a slot with url as key |
removeSlot | Delete the slot specified by url |
hasSlot | Whether it has the slot specified by url |
update | Submit data to the slot specified by url |
clear | Clear buffered data specified by url |
Type
Type name | Describe |
---|---|
regulatorFunc | Speed regulator notify function type |
QVsoaRegulator::QVsoaRegulator(int periodMs, QObject *parent)
Regulator constructor to adjust the frequency of publish or message to periodMs
.
periodMs
Regulator interval time.
vsoa_regulator_t *QVsoaRegulator::native()
Gets the vsoa_regulator_t object of the Regulator.
Returns
vsoa_regulator_t object.
bool QVsoaRegulator::setRegulatorPeriod(int periodMs)
The period time of the Regulator is periodMs
.
periodMs
period to set in milliseconds.Returns
true
if successful,false
otherwise.
bool QVsoaRegulator::addSlot(const QString &url, const regulatorFunc &ondelay, size_t bufSize)
Add a slot to the specified url
, and when the preset time is reached, the ondelay
function is called. The bufSize
is the maximum payload length that this slot can saved.
url
url for the slot to install.ondelay
Speed regulator notify function.bufSize
The maximum payload length that this slot can saved.Returns
true
if successful,false
otherwise.
bool QVsoaRegulator::removeSlot(const QString &url)
Removes a slot from the specified url
.
url
URL.Returns
true
if successful,false
otherwise.
bool QVsoaRegulator::hasSlot(const QString &url, size_t *bufSize)
Whether it has the slot specified by url
. bufSize
is the preset size for the addSlot method.
url
URL.bufSize
The bufSize passed to the addSlot method.Returns
true
if the slot is installed on the url,false
otherwise.
bool QVsoaRegulator::update(const QString &url, const QVsoaPayload &payload)
Submit data to the slot specified by url
.
url
URL.payload
payload to be updated.Returns
true
on success,false
otherwise.
bool QVsoaRegulator::clear(const QString &url)
Clear buffered data specified by url
.
url
URL.Returns
true
on success,false
otherwise.
Examples
// Initialize the QVsoa Server
...
QVsoaRegulator regulator(2000);
auto publishFunc = [&server](const QString &url, const QVsoaPayload &payload) {
server.publish(url, payload);
};
regulator.addSlot(url, publishFunc, 4096);
// Other logical processing
...
// Update the data to the regulator
regulator.update(url, payload);
...
Multi-threading support for QVSOA
QVSOA also has good support for multi-threaded cases, and we can continue to use the previous Qt multi-threaded development experience to develop multi-threaded applications for QVSOA. A simple example.
#include <QCoreApplication>
#include <QVsoa>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
// Create a thread on which our server will run.
QThread thread = new QThread;
// We can start this thread at any time.
thread.start();
// Create a server and move it to our thread.
QVsoaServer *server = new QVsoaServer("Test server");
server->moveToThread(serverTherad);
...
// Other code.
...
return a.exec();
}