OPENCLIENT RPC, събития и споделени връзки
OPENCLIENT(url, [id]) е вграденият клиент на протокола Open Platform. Преобразува URL адресите http/https в ws/wss. Логическите клиенти с един и същ URL споделят един WebSocket. .online(fn) получава метаданните {type:'init',id:...} на сървъра; .message(fn) получава непоискани съобщения. .rpc(message) връща promise; .send(message, callback, [filter], [timeoutMs]) използва callback; .cmd(message) изпраща без изчакване. .remove() затваря физическия сокет едва след като последният му логически клиент бъде премахнат.
Примерът включва локален протокол сървър. callbackid, error и response са протоколови полета. Времето за обаждане е opt-in; зададете един за заявки, които изискват срок.
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(); }
}