JSON-RPC.NET(https://github.com/Astn/JSON-RPC.NET) を使います。
インストール
VS2013を起動しNu-Get パッケージマネージャー コンソールを起動し、以下のコマンドを入力します
PM> Install-Package AustinHarris.JsonRpc
サンプル
今回はコンソールからJsonコードを渡してその結果を標準出力するタイプのものを作成。
それ以外のコードは https://github.com/Astn/JSON-RPC.NET/wiki にあるので、そちら参照。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AustinHarris.JsonRpc;
namespace ConsoleApplication13
{
public class ExampleCalculatorService : JsonRpcService
{
// JSON RPC で公開したいメソッドの先頭に[JsonRpcMethod]をつける
[JsonRpcMethod]
private int incr(int i) { return i + 1; }
}
class Program
{
static object[] services;
static void Main(string[] args)
{
// JsonRpcMethod が追加されているクラスのインスタンスを作成することで
// 公開されるようになる。
services = new object[] { new ExampleCalculatorService() };
var rpcResultHandler = new AsyncCallback(_ => Console.WriteLine(((JsonRpcStateAsync)_).Result));
// コンソールからJsonコードを待ち受ける。空行で終了。
for (string line = Console.ReadLine(); !string.IsNullOrEmpty(line); line = Console.ReadLine())
{
var async = new JsonRpcStateAsync(rpcResultHandler, null);
async.JsonRpc = line;
JsonRpcProcessor.Process(async);
}
}
}
}
使い方
上記コードをビルドして起動した後、以下のコードを入力
{'method':'incr', 'params':[5], 'id':1}
結果は以下のように出力される
{"jsonrpc":"2.0","result":6,"id":1}
エラーならこう
{"jsonrpc":"2.0","error":{"code":-32601,"message":"Method not found","data":"The method does not exist / is not available."},"id":1}
まとめ
上記コードではrpcResultHandler で受信したデータを標準出力に表示していますが、Jsonパーサー等を使用して変換して内部処理に使えるようにすると応用範囲が広くなるかもしれませんね。