ForgeTotal.js 5
en

Total.js 5

OPENCLIENT RPC, events and shared connections

Total.js 5 · total5@0.0.19 total5reference Executed against Total.js 5

OPENCLIENT(url, [id]) is the native Open Platform protocol client. It converts http/https URLs to ws/wss. Logical clients with the same URL share a WebSocket. .online(fn) receives the server's {type:'init',id:...} metadata; .message(fn) receives unsolicited messages. .rpc(message) returns a promise; .send(message, callback, [filter], [timeoutMs]) uses a callback; .cmd(message) sends without waiting. .remove() closes the physical socket only after its last logical client is removed.

The example includes a local protocol server. callbackid, error and response are protocol fields. A callback timeout is opt-in; set one for requests that need a deadline. Keep real platform credentials and URLs in server configuration.

controllers/open.js
exports.install = function() {
	ROUTE('SOCKET /fixture/', fixture);
	ROUTE('GET /openclient/', exercise);
};
function fixture() {
	var server = this;
	server.on('open', function(client) {
		client.send({ type: 'init', id: 'local-fixture', version: 1 });
	});
	server.on('message', function(client, message) {
		if (message.type === 'ignore')
			return;
		if (message.type === 'event') {
			client.send({ type: 'notice', value: message.value });
			return;
		}
		client.send({ callbackid: message.callbackid, error: message.type === 'fail' ? 'denied' : null, response: { value: message.value } });
	});
}
async function exercise($) {
	var a;
	var b;
	try {
		var url = $.hostname('/fixture/');
		a = OPENCLIENT(url, 'first');
		await new Promise(function(resolve, reject) {
			var timer = setTimeout(() => reject(new Error('init deadline')), 2000);
			a.online(function(meta) { if (meta) { clearTimeout(timer); resolve(); } });
		});
		b = OPENCLIENT(url, 'second');
		var shared = a.ws === b.ws;
		var sum = await a.rpc({ type: 'echo', value: 7 });
		var event = new Promise(resolve => a.message(resolve));
		a.cmd({ type: 'event', value: 9 });
		var notice = await event;
		var denied = await new Promise(resolve => a.send({ type: 'fail' }, err => resolve(String(err)), 300));
		var timeout = await new Promise(resolve => a.send({ type: 'ignore' }, err => resolve(String(err)), 50));
		a.remove();
		a = null;
		var alive = await b.rpc({ type: 'echo', value: 11 });
		var meta = b.meta;
		b.remove();
		b = null;
		$.json({ shared: shared, sum: sum, notice: notice, denied: denied, timeout: timeout, alive: alive, meta: meta });
	} catch (e) { $.invalid(e); }
	finally { if (a) a.remove(); if (b) b.remove(); }
}