Overview

更新时间:
2024-05-17
下载文档

Overview

VSOA is the abbreviation of Vehicle SOA presented by ACOINFO, 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:

  1. Support resource tagging of unified URL
  2. Support URL matching subscribe and publish model
  3. Support Real-Time Remote Procedure Call
  4. Support parallel multiple command sequences
  5. Support reliable and unreliable data publishing and datagram
  6. Support multi-channel full-duplex high speed parallel data stream
  7. Support network QoS control
  8. Easily implement server fault-tolerant design
  9. Supports multiple language bindings

VSOA is a dual-channel communication protocol, using both TCP and UDP, among which the API marked with quick uses the UDP channel. The quick channel is used for high-frequency data update channels. Due to the high data update frequency, the requirements for communication reliability are not strict. It should be noted that UDP channel cannot pass through NAT network, so please do not use quick channel in NAT network.

The total url and payload length of the VSOA data packet cannot exceed 256KBytes - 20Bytes and 65507Bytes - 20Bytes on quick channel, so if you need to send a large amount of data, you can use the VSOA data stream.

User can use the following code to import the vsoa package.

import com.acoinfo.vsoa.*;

Support

The following shows vsoa package APIs available.

 Static MethodCallback Method
Server
server.start
server.close
server.count
server.address
server.getTls
server.onClient
server.onSubscribe
server.onUnsubscribe
server.onData
server.on
server.publish
server.isSubscribed
server.sendTimeout
server.createStream
Client
client.connect
client.close
client.ping
client.subscribe
client.unsubscribe
client.call
client.datagram
client.createStream
client.getPeerName
client.getTls
client.isConnected
client.sendTimeout
client.onConnected
client.onMessage
client.onError
client.onSubscribe
client.onUnsubscribe
client.onDatagram
Client.fetch
Regulator
regulator.close
regulator.slot
regulator.unslot
regulator.onMessage
Position
position.start
position.stop
position.onQuery
position.lookup

ServerOption Class

ServerOption class is used for Server class constructor.

ServerOption(String info, String passwd)

ServerOption(String info, String passwd, boolean syncCB)

ServerOption(String info, String passwd, boolean syncCB, int poolSize)

The arguments of ServerOption constructor are as follows:

  • info {String} Server information description JSON string (must contain the name field).
  • passwd {String} Connection password. If set to null, no password is required.
  • syncCB {boolean} If syncCB is setted to true, only one thread can call user-defined callback at the same time. default : false.
  • poolSize {int} Server thread pool size, user-defined callback will be called by threads in the thread pool. default : 10.

TlsOption Class

TlsOption class is used for Server and Client class when TLS connection is used.

TlsOption (String name)

TlsOption (String name, String kmFile, String kmStorePasswd, String keyPasswd)

TlsOption (String name, String tmFile, String tmStorePasswd)

TlsOption (String name, String kmFile, String kmStorePasswd, String keyPasswd, String tmFile, String tmStorePasswd)

The arguments of TlsOption constructor are as follows:

  • name {String} TLS server name.
  • kmFile {String} Java keystore file. default: null.
  • kmStorePasswd {String} keystore password. default: null.
  • keyPasswd {String} key password. default: null.
  • tmFile {String} Java truststore file. default: null.
  • tmStorePasswd {String} truststore password. default: null.

Payload Class

Payload class is used for data transmission between client and server.

Payload (String param, byte[] data)

Payload(String param, byte[] data, int offset, int length)

The arguments of Payload constructor are as follows:

  • param {String} Parameters of packet, null for no param.
  • data {byte[]} Data for packet, null for no data.
  • offset {int} If data exists, this member indicates the offset of data. defaut 0.
  • length {int} If data exists, this member indicates the length of data. defaut 0.

VSOA Server Class

The server side API class.

Server(ServerOption opt)

The arguments of Server constructor are as follows:

  • opt {ServerOption} Server configuration.

Example

ServerOption opt = new ServerOption("{\"name\":\"Test server\"}", "123456", false, 10);
Server server = new Server(opt);

void close()

Close VSOA server.

boolean start(SocketAddress address, TlsOption tlsOpt)

  • Returns: {boolean} Whether the operation was successful.

Start the server, The arguments of this function are as follows:

  • address {SocketAddress} Server socket address.
  • tlsOpt {TlsOption} TLS security configuration. If the server is not a secure server, set tlsOpt to null.

If the server is a secure connection server, you need to set the tlsOpt parameter, please refer to the TlsOption class description.

Example

ServerOption opt = new ServerOption("Test server", "123456", false, 10);
Server server = new Server(opt);
// Start server
InetSocketAddress address = new InetSocketAddress("localhost", 3000);
server.start(address, null);

If the port bound at start is 0, the system will automatically assign a port. At this time, the VSOA server TCP and UDP ports are different, and the client needs to use version 1.0.1 or later to support.

int count()int count(boolean link)

  • Returns: {int} Current clients count.

Get the number of connected clients.

  • link {boolean} ture to get all clients, false to get authorized clilents. default: false.

InetSocketAddress address()

  • Returns: {InetSocketAddress} Server address.

Get the current server TCP / TLS address.

TlsOption getTls()

  • Returns: {TlsOption} TLS option.

Get Server TLS option.

boolean publish(String url, Payload payload)

boolean publish(String url, Payload payload, boolean quick)

  • Returns: {boolean} Whether the operation was successful.

Publish a message, all clients subscribed to this URL will receive this message. The arguments of this function are as follows:

  • url {String} Remote client.
  • payload {Payload} payload to publish.
  • quick {boolean} Whether to use the quick publish channel. default: false.

URL matching: URL uses '/' as a separator, for example: '/a/b/c', if the client subscribes to '/a/', the server publish '/a', '/a/b' or '/a/b/c' message, the client will be received.

Example

Server server = new Server(...);

server.publish('/a/b/c');
server.publish('/a/b/c', new Payload("{ \"hello\": \"'hello\" }", null));
server.publish('/a/b/c', new Payload("{ \"hello\": \"'hello\" }", new byte[] {1, 2, 3}));

If a large number of high-frequency publish are required and delivery is not guaranteed, quick publish can be used. Bug the quick type publish cannot traverse a NAT network, so the quick publish interface is not allowed in a NAT network. quick publish uses a different channel than publish, quick publish does not guarantee the order of arrival.

boolean isSubscribed(String url)

  • Returns: {boolean} Whether the specified URL is subscribed by clients.

Whether the specified URL is subscribed. When the return value is true, it means that the specified URL is subscribed by at least one client.The arguments of this function are as follows:

  • url {String} URL.

void sendTimeout(int timeout)void sendTimeout(int timeout, boolean curclis)

Set current server send timeout. The arguments of this function are as follows:

  • timeout {int} Send timeout.
  • curclis {boolean} Whether to set the currently connected client at the same time.

When the server is created, it will use the default send timeout (100 ms), this function is used to modify this setting, all clients will use this setting by default.

Stream createStream(int timeout)

  • Returns: {Stream}

Create a stream to wait for the client stream to connect. The arguments of this function are as follows:

  • timeout {int} Timeout value for waiting for client stream connection. Recommend : Stream.DEF_TIMEOUT.

You can refer to the Stream class documents for operation.

Example

Server server = new Server(...);
server.on("/read", new CBOnCall() {
	@Override
	public boolean Callback(String url, CliHandle client, Request req, Payload payload) {
		byte[] data = new byte[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
		Stream stream = server.createStream(Stream.DEF_TIMEOUT);
		client.reply(Constant.SUCCESS, req.seqno, null, stream.getTunid());
		if (!stream.waitForConnect()) {
			System.out.println("Stream timeout");
		}
		stream.write(data);
		stream.close();
		return true;
	}
});

void onClient(CliHandle client, boolean link)

  • {Function} Callback function can be overloaded.

This function is called when a client is connected or disconnected. The arguments of this callback function are as follows:

  • client {CliHandle} Remote client handle.
  • link {boolean} Connect or disconnect.

Example

Server server = new Server(...) {
	@Override
	public void onClient(CliHandle client, boolean link) {
		System.out.println("Client link " + link + " address: " + client.address().toString());
	}
};

void onSubscribe(String[] urls)

This client is subscribed to the specified URL events.

  • urls {String} Subscribe URLs.

void onUnsubscribe(String[] urls)

This client is unsubscribed to the specified URL events. If the URL is null, it means unsubscribe from all events.

  • urls {String} Unsubscribe URLs.

void onData(CliHandle client, String url, Payload payload, boolean quick)

  • {Function} Callback function can be overloaded.

This function is called when the server receives a DATAGRAM type packet. The arguments of this callback function are as follows:

  • client {CliHandle} Remote client handle.
  • url {String} This datagram URL.
  • payload {Payload} This datagram payload data.
  • quick {boolean} Whether this datagram comes from the quick channel.

Example

Server server = new Server(...) {
	@Override
	public void onData(CliHandle client, String url, Payload payload, boolean quick) {
		System.out.println("Datagram address: " + client.address().toString() + " url:" + url + " payload:" + payload.param);
	}
};

NOTICE: Usually DATAGRAM type data is used to transmit some data that does not require confirmation, for example, VSOA's DATAGRAM data packets can be used to build a VPN network.

void on(String url, CBOnCall cb)

Register RPC callback for url, The arguments of this function are as follows:

  • url {String} url.
  • cb {CBOnCall} callback object, cb.callback() is called when the client calls Client.call();

Example

Server server = new Server(...);

// Echo payload
server.on("/echo", new CBOnCall() {
	@Override
	public boolean Callback(String url, CliHandle client, Request req, Payload payload) {
		client.reply(Constant.SUCCESS, req.seqno, payload);
		return true;
	}
});

// Strictly match '/a/b/c' path
server.on("/a/b/c", new CBOnCall() {
	@Override
	public boolean Callback(String url, CliHandle client, Request req, Payload payload) {
		client.reply(Constant.SUCCESS, req.seqno, payload);
		return true;
	}
});

// Match '/a/b/c' and '/a/b/c/...'
server.on("/a/b/c/", new CBOnCall() {
	@Override
	public boolean Callback(String url, CliHandle client, Request req, Payload payload) {
		client.reply(Constant.SUCCESS, req.seqno, payload);
		return true;
	}
});

// Default match
server.on("/", new CBOnCall() {
	@Override
	public boolean Callback(String url, CliHandle client, Request req, Payload payload) {
		client.reply(Constant.SUCCESS, req.seqno, payload);
		return true;
	}
});

// Delay echo
server.on('/delayecho', new CBOnCall() {
	@Override
	public boolean Callback(String url, CliHandle client, Request req, Payload payload) {
		Thread.sleep(1000);
		client.reply(Constant.SUCCESS, req.seqno, payload);
		return true;
	}
});

When a remote client generates an RPC request, the server will receive the corresponding request event, usually the event name is the requested URL matched. The server can reply to RPC calls through the CliHandle.reply function.

RPC URL match rules

PATHRPC match rules
"/"Default URL listener.
"/a/b/c"Only handle "/a/b/c" path call.
"/a/b/c/"Handle "/a/b/c" and "/a/b/c/..." all path calls.

NOTICE: If both "/a/b/c" and "/a/b/c/" RPC handler are present, When the client makes a "/a/b/c" RPC call, "/a/b/c" handler is matched before "/a/b/c/".

CBOnCall class

RPC callback class.

boolean Callback(String url, CliHandle client, Request req, Payload payload)

  • Returns: {boolean} success or failed. RPC callback function, this function is call when the client calls Client.call().The arguments of this callback function are as follows:
  • url {String} the client called url.
  • client {CliHandle} Remote client handle.
  • payload {Payload} The RPC payload data.

Request class

Remote client request class.

Request(String url, int seqno, int method)

The arguments of Request constructor are as follows:

  • url {String} Request URL.
  • seqno {int} Command sequence number.
  • method {int} Operation method.

Possible values of method include Request.VSOA_METHOD_GET (0) and Request.VSOA_METHOD_SET (1).

VSOA RPC Method

Similar to HTTP, the client requests the server with the method parameter.

MethodValue
Request.VSOA_METHOD_GET0
Request.VSOA_METHOD_SET1

CliHandle class

Remote client handle in server.

void close()

Close this remote client connection.

boolean isSubscribed(String url)

  • Returns: {boolean} Whether the specified URL is subscribed by this client.

Whether the specified URL is subscribed. The arguments of this function are as follows:

  • url {String} URL.

InetSocketAddress address()

  • Returns: {InetSocketAddress} Remote client address.

Get this remote client address.

boolean datagram(String url, Payload payload)

boolean datagram(String url, Payload payload, boolean quick)

  • Returns: {boolean} Success or failed.

Send datagram packets to client. The arguments of this function are as follows:

  • url {String} datagram URL.
  • payload {Payload} This datagram payload data.
  • quick {boolean} Whether to use the quick channel. default: false.

NOTICE: Usually DATAGRAM type data is used to transmit some data that does not require confirmation, for example, VSOA's DATAGRAM data packets can be used to build a VPN network.

boolean reply(int status, int seqno, Payload payload)

boolean reply(int status, int seqno, Payload payload, int tunid)

  • Returns: {boolean} Success or failed.

Send reply packet to client. The arguments of this function are as follows:

  • status {int} Return status code.
  • seqno {int} Command sequence number.
  • payload {Payload} This reply payload data.
  • tunid {int} Server tunnel stream id, optional.

Server RPC reply, The valid value of code is 0 - 255, where 0 means success, and other values mean failure, where vsoa.code contains the following failure values, and the user-defined failure value is recommended to be 128 ~ 254.

Status CodeValueDescription
vsoa.code.SUCCESS0Call succeeded
vsoa.code.PASSWORD1Wrong password
vsoa.code.ARGUMENTS2Parameter error
vsoa.code.INVALID_URL3Invalid URL
vsoa.code.NO_RESPONDING4Server not responding
vsoa.code.NO_PERMISSIONS5No permission
vsoa.code.NO_MEMORY6Out of memory
vsoa.code.PROXY7Proxy error (payload.param.error indicates the error message)

NOTICE: seqno is very important, it must be consistent with the seqno of the RPC request.

void setKeepAlive(boolean on)

Set a client connection keepalive option on or off. The arguments of this callback function are as follows:

  • on {boolean} Turn tcp keepalive option on or off.

Example

Server server = new Server(...) {
	@Override
	public void onClient(CliHandle client, boolean link) {
		cli.setKeepAlive(true);
	}
};

NOTICE: The connection keepalive option depends on the operating system configuration. In Windows, Create the following entries in the registry path HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters

KeepAliveTime Time in milliseconds, after which a connection is considered idle before sending keepalive probes.

KeepAliveInterval Interval in milliseconds, between successive Keepalive probes.

TcpMaxDataRetransmissions Number of consecutive keepalive probes to be sent.

In Linux, Add the following lines to the /etc/sysctl.conf file:

net.ipv4.tcp_keepalive_time=<desired_time> Time in seconds, after which a connection is considered idle before sending keepalive probes.

net.ipv4.tcp_keepalive_intvl=<desired_interval> Interval in seconds, between successive keepalive probes.

net.ipv4.tcp_keepalive_probes=<desired_probes> Number of consecutive keepalive probes to be sent.

boolean priority(int prio)

  • Returns: {boolean} Success or failed.

Set the specified remote client priority. The arguments of this callback function are as follows:

  • prio {int} New priority.

The allowed priority range is 0 ~ 5, 0 is the lowest priority, 5 is the highest priority, and the initial priority of each client is 0. The priority controls the order in which the publish is sent, and the underlying network packet QoS, please set according to the situation.

Example

Server server = new Server(...) {
	@Override
	public void onClient(CliHandle client, boolean link) {
		client.priority(3);
	}
};

int getPriority()

  • Returns: {int} priority of client.

Get priority of the client.

boolean isConnected()

  • Returns: {boolean} connection status.

Get connection status of client.

void setTimeout(int timeout)

  • timeout {int} Set network send timeout(ms).

Set the client packet sending timeout, default: wait for sending when the network is blocked (0).

boolean setAuthed(boolean authed)

  • Returns: {boolean} the result of setting operation.

Set client’s authorization status. The arguments of this function are as follows:

  • authed {boolean} the authorization status.

boolean getAuthed()

  • Returns: {boolean} the authorization status.

The server can set and obtain the authorization status of the client. When a client connects to the server and has passed the password check, the client’s authed status is true at this time, and he can receive the server’s publish information at the same time. When the server still needs to perform For additional independent authorization checks, this state can be set to false when the client just connects, at this time the client will not be able to get the publish message until the client passes the server's independent authorization check.

Example

Server server = new Server(...) {
	@Override
	public void onClient(CliHandle client, boolean link) {
		if (link) {
			client.setAuthed(false);
		}
	}
	
	server.on("/auth", new CBOnCall() {
		@Override
		public boolean Callback(String url, CliHandle client, Request req, Payload payload) {
			if (/* Independent Authorization Verify */) {
				client.setAuthed(true);
				/* The authorization verification is successful, 
		 		 * and the server's publish information can be received */
				client.reply(Constant.SUCCESS, req.seqno, payload);
			} else {
				client.reply(AUTH_ERROR_CODE, req.seqno, payload);
			}

			return true;
		}
	});
};

ClientOption class

ClientOption class is used for Client class constructor.

ClientOption(String passwd)

ClientOption(String passwd, boolean syncCB)

ClientOption(String passwd, boolean syncCB, int poolSize)

ClientOption(String passwd, int pingInterval, int pingTimeout, int pingMaxLost)

ClientOption(String passwd, int pingInterval, int pingTimeout, int pingMaxLost, int pingTurbo)

ClientOption(String passwd, int pingInterval, int pingTimeout, int pingMaxLost, boolean syncCB)

ClientOption(String passwd, int pingInterval, int pingTimeout, int pingMaxLost, int pingTurbo, boolean syncCB)

ClientOption(String passwd, int pingInterval, int pingTimeout, int pingMaxLost, boolean syncCB, int poolSize)

ClientOption(String passwd, int pingInterval, int pingTimeout, int pingMaxLost, int pingTurbo, boolean syncCB, int poolSize)

The arguments of ClientOption constructor are as follows:

  • passwd {String} password when connect to server.
  • pingInterval {int} Ping interval time, must be greater than 10ms. Optional.
  • pingTimeout {int} Ping timeout, must be less than pingInterval default: same as pingInterval. Optional.
  • pingMaxLost {int} How many consecutive ping timeouts will drop the connection. default: 3.
  • pingTurbo {int} Fast ping period. must be less or equal than pingInterval, pingInterval should be an integer multiple of pingTurbo. Optional.
  • syncCB {boolean} If syncCB is setted to true, only one thread can call user-defined callback at the same time. default : false.
  • poolSize {int} Server thread pool size, user-defined callback will be called by threads in the thread pool. default : 10.

VSOA Client Class

The client side API class.

Client(ClientOption clientOption)

The arguments of Client constructor are as follows:

  • clientOption {ClientOption} Client options.

If you set clientOption.pingInterval, after the client connects to the server, it will immediately start periodic ping operations, and always check the communication link and whether the server is normal.

Example

Client client = new Client(new ClientOption(null));
Client client = new Client(new ClientOption("123456"));
Client client = new Client(new ClientOption("123456", 6000, 4000, 3, false));

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 pingTurbo parameter, the minimum value is 25ms. 0 means disable turbo ping.

Example

Client client = new Client(new ClientOption("123456", 6000, 4000, 3, 200, false));

boolean connect(SocketAddress address, TlsOption tlsOpt, int timeout)

  • Returns: {boolean} success or failed.

Connect to the specified VSOA server. The arguments of this function are as follows:

  • saddr {SocketAddress} Server socket address.
  • tlsOpt {TlsOption} TLS security configuration. Optional.
  • timeout {int} Connection timeout. Recommend : Constant.VSOA_DEF_CONN_TIMEOUT.

If the server is a secure connection server, you need to set the tlsOpt parameter, please refer to the TlsOption class description.

Example

Client client = new Client(new ClientOption("123456"));
SocketAddress address = new InetSocketAddress("localhost", 3001)
if (!client.connect(address, null, Constant.VSOA_DEF_CONN_TIMEOUT)) {
	System.out.println("Connected with server failed" + address.toString());
	return;
}

boolean connect(String url, TlsOption tlsOpt, int timeout)

  • Returns: {boolean} Success or failed.

Connect to the specified VSOA server. The arguments of this function are as follows:

  • url {String} Server url .
  • tlsOpt {TlsOption} TLS security configuration. Optional.
  • timeout {int} Connection timeout. Recommend : Constant.VSOA_DEF_CONN_TIMEOUT.

If the server is a secure connection server, you need to set the tlsOpt parameter, please refer to the TlsOption class description.

Example

Client client = new Client(new ClientOption("123456"));
if (!client.connect("vsoa://vsoa.acoinfo.com", null, Constant.VSOA_DEF_CONN_TIMEOUT)) {
	System.out.println("Connected with server failed" + address.toString());
	return;
}

void close()

Close the current client. After this client is closed, it is allowed to call the Client.connect method to reconnect to the server.

boolean ping(CBPing callback, int timeout)

  • Returns: {boolean} success or failed.

Ping the server to check whether the server connection is normal. The arguments of this function are as follows:

  • callback {CBPing} ping callback object.
  • timeout {int} Response timeout. Recommend : Constant.VSOA_DEF_TIMEOUT.

Example

Client client = new Client(new ClientOption("123456"));
client.connect("vsoa://vsoa.acoinfo.com", null, Constant.VSOA_DEF_CONN_TIMEOUT);
client.ping(new CBPing() {
	@Override
	public void callback(Error error) {
		if (error != null) {
			System.out.println("Ping error:" + error.message);
		} else {
			System.out.println("Ping ok");
		}
	}
}, 3000);

Under normal circumstances, TCP connection disconnection can be detected by override Client.onError() function, and periodic Ping operations can detect physical connection failure errors.

boolean subscribe(String url, CBSubscribe cbSubscribe)

boolean subscribe(String url, CBSubscribe cbSubscribe, int timeout)

boolean subscribe(String[] urls, CBSubscribe cbSubscribe)

boolean subscribe(String[] urls, CBSubscribe cbSubscribe, int timeout)

  • Returns: {boolean} success or failed.

Subscribe to the specified event (URL), when the server sends the corresponding event, the Client can receive the event. The arguments of this function are as follows:

  • url {String} Event that need to be subscribed.
  • urls {String[]} Events that need to be subscribed.
  • callback {CBSubscribe} Subscription callback object
  • timeout Timeout. Recommend : Constant.VSOA_DEF_TIMEOUT.

Example

Client client = new Client(new ClientOption("123456")){
	@Override
	public void onMessage(String url, Payload payload) {
		System.out.println("[CLIENT] received event: " + url + " payload: " + payload.param);
	}
};
client.connect("vsoa://vsoa.acoinfo.com", null, Constant.VSOA_DEF_CONN_TIMEOUT);

// Single subscription
client.subscribe("/a", new CBSubscribe() {
	@Override
	public void callback(Error error) {
		System.out.println("[CLIENT] Subscribe :" + (error != null ? "Error" : "OK"));
	}
});

// Multi subscription
client.subscribe(new String[] {"/a", "/b", "/c"}, new CBSubscribe() {
	@Override
	public void callback(Error error) {
		System.out.println("[CLIENT] Subscribe :" + (error != null ? "Error" : "OK"));
	}
});

Subscribe URL match rules

PATHSubscribe match rules
"/"Catch all publish message.
"/a/b/c"Only catch "/a/b/c" publish message.
"/a/b/c/"Catch "/a/b/c" and "/a/b/c/..." all publish message.

boolean unsubscribe(String url, CBSubscribe cbSubscribe)

boolean unsubscribe(String url, CBSubscribe cbSubscribe, int timeout)

boolean unsubscribe(String[] urls, CBSubscribe cbSubscribe)

boolean unsubscribe(String[] urls, CBSubscribe cbSubscribe, int timeout)

  • Returns: {boolean} success or failed.

Unsubscribe the specified event, if url is not specified, unsubscribe all events. The arguments of this function are as follows:

  • url {String} Event that need to be unsubscribed.
  • urls {String[]} Events that need to be unsubscribed.
  • callback {CBSubscribe} Unsubscription callback object
  • timeout {int} Timeout. Recommend : Constant.VSOA_DEF_TIMEOUT.

boolean call(String url, int method, Payload payload, CBCall cbCall, int timeout)

  • Returns: {boolean} success or failed.

Make an RPC call. The arguments of this function are as follows:

  • url {String} RPC call url.
  • method {int} RPC method, Request.VSOA_METHOD_GET (0) or Request.VSOA_METHOD_SET (1). default: Request.VSOA_METHOD_GET.
  • payload {Payload} RPC payload. Optional.
  • cbCall {CBCall} RPC callback object.
  • timeout {int} Timeout. Recommend : Constant.VSOA_DEF_TIMEOUT.

Example

  • Simple call
client.call("/a/b/c'", Request.VSOA_METHOD_GET, null, new CBCall() {
	@Override
	public void callback(Error error, Payload payload, int tunid) {
		if (error != null) {
			System.out.println("RPC call error:" + error.message);
		} else {
			System.out.println("RPC call reply:" + payload.param);
		}
	}
}, 2000);
  • Setting
Payload payload = new Payload("{param: { hello: 'hello' }}", new byte[] {5, 4, 3, 2, 1, 0});
client.call("/a/b/c'", Request.VSOA_METHOD_SET, payload, new CBCall() {
	@Override
	public void callback(Error error, Payload payload, int tunid) {
		if (error != null) {
			System.out.println("RPC call error:" + error.message);
		} else {
			System.out.println("RPC call reply:" + payload.param);
		}
	}
}, 2000);
  • Get stream data
client.call("/a/b/c'", Request.VSOA_METHOD_GET, null, new CBCall() {
	@Override
	public void callback(Error error, Payload payload, int tunid) {
		if (error != null) {
			System.out.println("RPC call error:" + error.message);
		} else {
			Stream stream = client.createStream(tunid, Stream.DEF_TIMEOUT);
			if (stream != null) {
				byte[] data;
				while ((data = stream.read()) != null) {
					String strData = "";
					for(int i = 0; i < data.length; i++) {
						strData += Integer.toHexString(data[i]);
					}
					System.out.println("Stream received:" + strData);
				}
			}
		}
	}
}, 2000);

The error generated by the client If error.message is status, you can get the status code returned by the server through error.status.

boolean datagram(String url, Payload payload)

boolean datagram(String url, Payload payload, boolean quick)

  • Returns: {boolean} Success or failed.

Client sends DATAGRAM packet to server. This communication server does not confirm and does not guarantee successful communication. The arguments of this function are as follows:

  • url {String} datagram URL.
  • payload {Payload} This datagram payload data.
  • quick {boolean} Whether use quick channel. default: false.

NOTICE: Usually DATAGRAM type data is used to transmit some data that does not require confirmation, for example, VSOA's DATAGRAM data packets can be used to build a VPN network.

Stream createStream(int tunid, int timeout)

  • Returns: {Stream} Stream object.

Create a stream to connect with the server stream, you can refer to the Stream class related documents for operation. The arguments of this function are as follows:

  • tunid {int} Server tunnel stream id.
  • timeout {int} Timeout. Recommend : Stream.DEF_TIMEOUT.

Example

client.call("/read'", Request.VSOA_METHOD_GET, null, new CBCall() {
	@Override
	public void callback(Error error, Payload payload, int tunid) {
		if (error != null) {
			System.out.println("RPC call error:" + error.message);
		} else {
			Stream stream = client.createStream(tunid, Stream.DEF_TIMEOUT);
			if (stream != null) {
				byte[] data;
				while ((data = stream.read()) != null) {
					String strData = "";
					for(int i = 0; i < data.length; i++) {
						strData += Integer.toHexString(data[i]);
					}
					System.out.println("Stream received:" + strData);
				}
			}
		}
	}
}, 2000);

String getPeerName()

  • Returns: {String} server address.

Get server address of the connection.

TlsOption getTls()

  • Returns: {TlsOption} TLS option.

Get Client TLS option.

boolean isConnected()

  • Returns: {boolean} connection status.

Get connection status.

void sendTimeout(int timeout) Set client send timeout. The arguments of this function are as follows:

  • timeout {int} Set network send timeout(ms).

Set the client packet sending timeout, the default waiting for the sending buffer to be valid is 500 ms.

void onDatagram(String url, Payload payload, boolean quick)

  • {Function} Callback function can be overloaded.

This function is called when the client receives a DATAGRAM type packet. The arguments of this callback function are as follows:

  • url {String} This datagram URL.
  • payload {Payload} This datagram payload data.
  • quick {boolean} Whether this datagram comes from the quick channel.

Example

Client client = new Client(...) {
	@Override
	public void onDatagram( String url, Payload payload, boolean quick) {
		if (url == null) {
			System.out.println("url null");
		}
		System.out.println("[CLIENT] Datagram from url:" + url + " payload:" + payload.param);
	}
};

void onMessage(String url, Payload payload, boolean quick)

  • {Function} Callback function can be overloaded.

For messages published by the server, if this client subscribes to the relevant URL, then when the server publishes the corresponding event, this client will be received, and this function will be called. The arguments of this callback function are as follows:

  • url {String} Server event URL.
  • payload {Object} Server event payload. Optional.
  • quick {boolean} Is it a quick publish message.

Example

Client client = new Client(...) {
	@Override
	public void onMessage( String url, Payload payload, boolean quick) {
		System.out.println("[CLIENT] received event: " + url + " payload: " + payload.param);
	}
};

void onConnected(String info)

  • {Function} Callback function can be overloaded.

This function is called when this client successfully connected to the server. The arguments of this callback function are as follows:

  • info {String} Server info.

Example

Client client = new Client(...) {
	@Override
	public void onConnected(String info) {
		System.out.println("[CLIENT] Connected with server:" + info);
	}
};

void onSubscribe(String[] urls)

  • {Function} Callback function can be overloaded.

This function is called when this client successfully subscribed to the specified events. The arguments of this callback function are as follows:

  • urls {String} urls.

Example

Client client = new Client(...) {
	@Override
	public void onSubscribe(String[] urls) {
		for (String url : urls) {
			System.out.println("[CLIENT] subscribe url:" + url);
		}
	}
};

void onUnsubscribe(String[] urls)

  • {Function} Callback function can be overloaded.

This function is called when this client successfully unsubscribed to the specified events. The arguments of this callback function are as follows:

  • urls {String} urls.

Example

Client client = new Client(...) {
	@Override
	public void onUnsubscribe(String[] urls) {
		for (String url : urls) {
			System.out.println("[CLIENT] unsubscribe url:" + url);
		}
	}
};

void onError(Error error)

  • {Function} Callback function can be overloaded.

This function will be called when the client generates an error. the user can call Client.close to close the client, and the client object can be call Client.connect again. The arguments of this callback function are as follows:

  • error {Error} Error object.

Example

Client client = new Client(...) {
	@Override
	public void onError(Error error) {
		System.out.println("[CLIENT] Client error:" + error.message);
		client.close();
	}
};

statit boolean fetch(String url, ClientOption clientOption, TlsOption tlsOpt, int method, Payload payload, CBCall cbCall, int timeout)

  • Returns: {boolean} Successs or failed.

Static function to make a RCP call, The arguments of this callback function are as follows:

  • url {String} RPC command url.
  • clientOption {ClientOption} RPC options.
  • tlsOpt {TlsOption} TLS connection options, null for no TLS connection.
  • method {int} RPC method. Request.VSOA_METHOD_GET (0) or Request.VSOA_METHOD_SET (1).
  • payload {Payload} RPC payload, null for no payload.
  • cbCall {CBCall} RPC callback object.
  • timeout {int} Timeout. Recommend : Constant.VSOA_DEF_TIMEOUT.

Example

// Fetch server /foo data
Client.fetch("vsoa://vsoa.acoinfo.com/foo", null, null, Request.VSOA_METHOD_GET, null, new CBCall() {
	@Override
	public void callback(Error error, Payload payload, int tunid) {
		if (error != null) {
			System.out.println("[CLIENT] Command /foo error:" + error.message);
		} else {
			System.out.println("[CLIENT] Command /foo reply:" + payload.param);
		}
	}
}, 2000);

Error class

Error class contains error infomation.

Error(String message)

Error(String message, int status)

The arguments of Error constructor are as follows:

  • message {String} Error message.
  • status {int} Server responded with an error status.

The possible errors are as follows:

Error MessageHas StatusDescription
'no responding'Server is not responding
'status'Server responded with an error status
'ping timeout'Periodic automatic ping timeout
'no network'Server connection lost
'no connection'Network is not connected
'parser error'Packet parser error
'closed'Client is closed

Stream class

Stream class is used for mass data transmission.

Stream(InetSocketAddress address, TlsOption tlsOpt, int timeout, boolean server)

Stream constructor is Called by Client.createStream and Server.createStream. The arguments of Stream constructor are as follows:

  • address {InetSocketAddress} Stream address. in server mode, address is the listen address, in client mode address is the server address to connect.
  • tlsOpt {TlsOption} TLS option connection, null for no tls connection.
  • timeout {timeout} in server mode, this is the timeout time for waiting for client stream connection, in client mode ,this is the timeout time for connectting to the server. Recommend : Stream.DEF_TIMEOUT.
  • server {boolean} server mode or client mode.

int write(byte[] data)

  • Returns: {int} date.length for sucdess, -1 for failed.

Write data to stream. The arguments of this callback function are as follows:

  • data {byte[]} data buffer to write.

byte[] read()

  • Returns: {byte[]} date buffer readed from stream, null for failed.

Read data from stream.

void close()

Close stream.

int getTunid()

  • Returns: {int} Tunid

Get tunid of stream.

boolean waitForConnect()

  • Returns: {boolean} Success or failed.

Waiting for client connecting, only works in server mode.

VsoaSocketAddress class

VsoaSocketAddress class is returned Position.loockup, it extends SocketAddress class.

VsoaSocketAddress(String address, int port, boolean security)

The arguments of VsoaSocketAddress constructor are as follows:

  • address {String} Address.
  • port {int} TCP port.
  • security {boolean} true a TLS server.

PositionItem class

Positionitem class is used for indicating a VSOA server information.

PositionItem(String name, int domain, String address, int port, boolean security)

The arguments of PositionItem constructor are as follows:

  • name {String} VSOA server name.
  • domain {name} Address domain Refer to tcp or socket module.
  • address {String} Address.
  • port {int} TCP port.
  • security {boolean} Whether the server is a TLS secure connection.

ReqItem class

'ReqItem' class is used for position request.

ReqItem(String name, int domain, String address, int port)

The arguments of ReqItem constructor are as follows:

  • name {String} VSOA server name in request.
  • domain {int} Domain in request.
  • address {String} client address.
  • port {int} client UDP port.

Regulator class

VSOA regulator provides the function of changing the speed of client subscription data. For example, the server publish period is 100ms, and the regulator can slow down the speed to receive once every 1000ms. Regulator(Client client, int period) The arguments of Regulator constructor are as follows:

  • client {Client} VSOA client object.
  • period {int} Fastest update period.

Create a VSOA regulator, period cannot be less than 1ms.

Example

Regulator regulator = new Regulator(client, 5000);

void close() Close VSOA regulator. This object cannot be used again.

boolean slot(String url)

  • url {String} Legal URL string.
  • Returns: {boolean} Success or failed.

Set a URL that needs to be changed. This URL can be a precise URL or a wildcard URL.

void unslot(String url)

  • url {String} Legal URL string.

Delete a URL that regulator.slot() has been called before.

void period(int period)

  • period {int} Fastest update period.

void onMessage(String url, Payload payload, boolean quick)

  • {Function} Callback function can be overloaded.

For messages published by the server, if the client associated with this regulator subscribes to the relevant URL, then when the server publishes the corresponding event, this function will be called. The arguments of this callback function are as follows:

  • url {String} Server event URL.
  • payload {Object} Server event payload. Optional.
  • quick {boolean} Is it a quick publish message. After changing the speed of the publish message event, developers do not need to repeatedly listen to the client’s message event.

For example, the server "/foo" url publishes very quickly, and we need to reduce the speed to 1s. You can use the following code:

Regulator regulator = new Regulator(client, 5000) {
	@Override
	public void onMessage( String url, Payload payload, boolean quick) {
		System.out.println("[REGULATOR] received event: " + url + " payload: " + payload.param);
	}
};
regulator.slot("/foo");

Position class

The Position service API.

Position(PositionItem[] servers, SocketAddress address)

VSOA Position Server provides the function of querying VSOA server address by service name, similar to DNS server. The arguments of Position constructor are as follows:

  • servers {PositionItem} The server static address table
  • address {SocketAddress} The UDP socket address of the Position server.

boolean start()

  • Returns: {boolean} Success or failed.

Start the position server.

void stop()

Stop the position server.

boolean replay(ReqItem reqItem, PositionItem server)

  • Returns: {boolean} Success or failed.

Send a replay to the client. The arguments of this callback function are as follows:

  • reqItem {ReqItem} Client request information.
  • server {PositionItem} VSOA server address.

This function can be called by user-defined onQuery function.

void onQuery(ReqItem reqItem)

User-defined callback function, it is called when a request can't be resolved by static server address table.

  • reqItem {ReqItem} Client request information.

Example

public static PositionItem servers[] = {
	new PositionItem("c_server", Constant.AF_INET, "127.0.0.1", 3001, false),
	new PositionItem("jsre_server", Constant.AF_INET, "127.0.0.1", 3002, false)
}

	position = new Position(servers, new InetSocketAddress("127.0.0.1", 3000)){
		@Override
		public void onQuery(ReqItem reqItem) {
			if (name == 'java_server') {
				replay(reqItem, new new PositionItem("java_server", Constant.AF_INET, "127.0.0.1", 3003, false));
			}
		}
	};
	position.start();
};

VsoaSocketAddress lookup(SocketAddress address, String name, int domain)

  • Returns: {VsoaSocketAddress} Server address.

Static function, query the network socket address corresponding to a VSOA service. The arguments of this callback function are as follows:

  • address {SocketAddress} Position server address.
  • name {String} VSOA server name.
  • domain {int} Query the server address of the specified domain. 0 for any domain.

Example

VsoaSocketAddress address = Position.lookup(new InetSocketAddress("localhost", 3000), "java_server", 0);

Lookup from the server specified by environment variable or configuration file.

VsoaSocketAddress address = Position.lookup(null, "java_server", 0);

If position server is specified, only the specified server will be queried, If the position server address has not been specified (address is null), this function will first use the environment variable VSOA_POS_SERVER to query, if not found, it will use the server query configured in C:\Windows\System32\drivers\etc\vsoa.pos (Windows) or /etc/vsoa.pos (UNIX compatible systems).

Constant class

Constant contains constants which are used by VSOA API.

VSOA Status Code

Similar to HTTP, the server responds with a status code to the client.

VSOA status code, the valid value of code is 0 ~ 255, where 0 means success, and other values mean failure, where vsoa.code contains the following failure values, and the user-defined failure value is recommended to be 128 ~ 254.

Status CodeValueDescription
Constant.SUCCESS0Call succeeded
Constant.PASSWORD1Wrong password
Constant.ARGUMENTS2Parameter error
Constant.INVALID_URL3Invalid URL
Constant.NO_RESPONDING4Server not responding
Constant.NO_PERMISSIONS5No permission
Constant.NO_MEMORY6Out of memory

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