C#中JSON-RPC客户端的示例代码

我需要一个简单的C#中的JSON-RPC 1.0客户端,最好使用.NET 2.0或更高版本。 我检查了JRock 0.9他们有几个样本,包括雅虎读者,但样本演示JSON,而不是JSON-RPC。 我知道我可以使用任何可用的JSON解析器来实现RPC部分,例如JRock或Microsoft的两个。 我更喜欢准备好样品。

2样品在这里

有两种不同的实现。 阅读整个post+检查附件

上面的示例使用HTTP请求。 这是一个与TCP一起使用的变体(Nil类只是一个用于没有返回值的请求的空类):

using System; using System.Collections.Generic; using System.IO; using System.Net; using Newtonsoft.Json.Linq; using AustinHarris.JsonRpc; using System.Linq; using System.Reactive.Linq; using System.Reactive.Subjects; using System.Reactive.Concurrency; using System.Net.Sockets; using System.Text; namespace JsonRpc { public class JsonRpcClient { private static object idLock = new object(); private static int id = 0; public Encoding encoding { get; set; } public JsonRpcClient(IPEndPoint serviceEndpoint, Encoding encoding) { this.serviceEndPoint = serviceEndpoint; this.encoding = encoding; } private static Stream CopyAndClose(Stream inputStream) { const int readSize = 256; byte[] buffer = new byte[readSize]; MemoryStream ms = new MemoryStream(); int count = inputStream.Read(buffer, 0, readSize); while (count > 0) { ms.Write(buffer, 0, count); count = inputStream.Read(buffer, 0, readSize); } ms.Position = 0; inputStream.Close(); return ms; } public IObservable> InvokeWithScheduler(string method, object arg, IScheduler scheduler) { var req = new AustinHarris.JsonRpc.JsonRequest() { Method = method, Params = new object[] { arg } }; return InvokeRequestWithScheduler(req, scheduler); } public IObservable> InvokeSingleArgument(string method, object arg) { var req = new AustinHarris.JsonRpc.JsonRequest() { Method = method, Params = new object[] { arg } }; return InvokeRequest(req); } public IObservable> InvokeWithScheduler(string method, object[] args, IScheduler scheduler) { var req = new AustinHarris.JsonRpc.JsonRequest() { Method = method, Params = args }; return InvokeRequestWithScheduler(req, scheduler); } public IObservable> Invoke(string method, object[] args) { var req = new AustinHarris.JsonRpc.JsonRequest() { Method = method, Params = args }; return InvokeRequest(req); } public IObservable> InvokeRequestWithScheduler(JsonRequest jsonRpc, IScheduler scheduler) { var res = Observable.Create>((obs) => scheduler.Schedule(()=>{ makeRequest(jsonRpc, obs); })); return res; } public IObservable> InvokeRequest(JsonRequest jsonRpc) { return InvokeRequestWithScheduler(jsonRpc, ImmediateScheduler.Instance); } private string sendAndReceive(string messageToSend) { string res = null; // Data buffer for incoming data. byte[] bytes = new byte[1024]; // Connect to a remote device. try { // Create a TCP/IP socket. Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp ); // Connect the socket to the remote endpoint. Catch any errors. try { socket.Connect(this.serviceEndPoint); Console.Write("Socket connected to "+socket.RemoteEndPoint.ToString()); // Encode the data string into a byte array. byte[] msg = encoding.GetBytes(messageToSend); // Send the data through the socket. int bytesSent = socket.Send(msg); // Receive the response from the remote device. int bytesRec = socket.Receive(bytes); res = encoding.GetString(bytes,0,bytesRec); Console.Write("Server response = "+res); // Release the socket. socket.Shutdown(SocketShutdown.Both); socket.Close(); } catch (ArgumentNullException ane) { Console.Write("ArgumentNullException : "+ane.ToString()); } catch (SocketException se) { Console.Write("SocketException : " + se.ToString()); } catch (Exception e) { Console.Write("Unexpected exception : " + e.ToString()); } } catch (Exception e) { Console.Write(e.ToString()); } return res; } private void makeRequest(JsonRequest jsonRpc, IObserver> obs) { JsonResponse rjson = null; string sstream = ""; try { int myId; lock (idLock) { myId = ++id; } jsonRpc.Id = myId.ToString(); } catch (Exception ex) { obs.OnError(ex); } try { var json = Newtonsoft.Json.JsonConvert.SerializeObject(jsonRpc)+"\r\n"; if (typeof(T).Equals(typeof(Nil))) { sendAndReceive(json); rjson = new JsonResponse(); } else { sstream = sendAndReceive(json); rjson = Newtonsoft.Json.JsonConvert.DeserializeObject>(sstream); } } catch (Exception ex) { obs.OnError(ex); } if (rjson == null) { string exceptionMessage = ""; try { JObject jo = Newtonsoft.Json.JsonConvert.DeserializeObject(sstream) as JObject; exceptionMessage = jo["Error"].ToString(); } catch(Exception ex){ exceptionMessage = sstream+"\r\n"+ex.Message; } obs.OnError(new Exception(exceptionMessage)); } else { obs.OnNext(rjson); } obs.OnCompleted(); } public IPEndPoint serviceEndPoint { get; set; } } } 

以下是通过Observables(Rx)公开的.net4客户端示例。 http://jsonrpc2.codeplex.com/SourceControl/changeset/view/13061#63133

这是一个几乎相同的wp7客户端,也通过Rx公开。 http://jsonrpc2.codeplex.com/SourceControl/changeset/view/13061#282775

这两个示例都是异步执行它们的工作,因此它们可能比您正在寻找的更复杂,除非您想要异步的示例。 🙂

祝好运!