JSON-RPC

Introduction

RPC communication is a way to call server-side functions directly from the client-side.
I wrote an example of a JSON-RPC server in the default www folder of Cendre. I will show you how to use it.

Server-side functions

In the '[..]/node_modules/cendre/www/ssjs/' folder, create an info.nodejs file.
You can write functions in it with the following form :

// Function with no argument.
exports.getInfos = function(c, end)
{
	end('infos');
};

// Function with two arguments.
exports.getMoreInfos = function(c, end, arg1, arg2)
{
	end(arg1 + ' infos ' + arg2);
};

Client requests

Add the following line in the head tag of your webpage.

<script type="application/javascript" src="/rpc-source/m_info/info"></script>

You can then make synchronous or asynchronous requests, depending you add a function or not as last argument.

// Synchronous request
var obj = m_info.getInfos();

if (obj.err)
{
	console.log('erreur : ' + obj.result);
}
else
{
	console.log(obj.result);
}

// Asynchronous request.
m_info.getMoreInfos('arg1', 'arg2', function(err, result)
{
	if (err)
	{
		console.log('erreur : ' + result);
		return;
	}

	console.log(result);
});

Browser support

                   Async Sync
Internet Explorer : Yes  Yes
      Opera 12.14 : Yes  Yes
          Firefox : Yes  Yes
           Chrome : Yes  Yes (since version 36)
           Safari : Yes  Yes