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

发布于 2024-07-24 00:49:51 字数 197 浏览 9 评论 0原文

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

I need a simple JSON-RPC 1.0 client in C#, preferably using .NET 2.0 or later.
I checked out JRock 0.9
They have several samples including Yahoo reader, but the samples demo JSON, not JSON-RPC.
I understand I could implement RPC part using any of the available JSON parsers, like JRock or two from Microsoft. I would prefer a ready sample.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

饮湿 2024-07-31 00:49:51

2 个示例

有两种不同的实现。 阅读全文+检查附件

2 Samples here

There are two different implementations. Read the whole thread + check the attachments

止于盛夏 2024-07-31 00:49:51

上面的示例适用于 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<JsonResponse<T>> InvokeWithScheduler<T>(string method, object arg, IScheduler scheduler)
        {
            var req = new AustinHarris.JsonRpc.JsonRequest()
            {
                Method = method,
                Params = new object[] { arg }
            };
            return InvokeRequestWithScheduler<T>(req, scheduler);
        }

        public IObservable<JsonResponse<T>> InvokeSingleArgument<T>(string method, object arg)
        {
            var req = new AustinHarris.JsonRpc.JsonRequest()
            {
                Method = method,
                Params = new object[] { arg }
            };
            return InvokeRequest<T>(req);
        }

        public IObservable<JsonResponse<T>> InvokeWithScheduler<T>(string method, object[] args, IScheduler scheduler)
        {
            var req = new AustinHarris.JsonRpc.JsonRequest()
            {
                Method = method,
                Params = args
            };
            return InvokeRequestWithScheduler<T>(req, scheduler);
        }

        public IObservable<JsonResponse<T>> Invoke<T>(string method, object[] args)
        {
            var req = new AustinHarris.JsonRpc.JsonRequest()
            {
                Method = method,
                Params = args
            };
            return InvokeRequest<T>(req);
        }

        public IObservable<JsonResponse<T>> InvokeRequestWithScheduler<T>(JsonRequest jsonRpc, IScheduler scheduler)
        {
            var res = Observable.Create<JsonResponse<T>>((obs) => 
                scheduler.Schedule(()=>{

                    makeRequest<T>(jsonRpc, obs);
                }));

            return res;
        }

        public IObservable<JsonResponse<T>> InvokeRequest<T>(JsonRequest jsonRpc)
        {
            return InvokeRequestWithScheduler<T>(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<T>(JsonRequest jsonRpc, IObserver<JsonResponse<T>> obs)
        {
            JsonResponse<T> 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<T>();
                }
                else
                {
                    sstream = sendAndReceive(json);
                    rjson = Newtonsoft.Json.JsonConvert.DeserializeObject<JsonResponse<T>>(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; }
    }
}

The samples above work with HTTP requests. Here's a variant that works with TCP (the Nil class is just an empty class used for requests with no return value):

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<JsonResponse<T>> InvokeWithScheduler<T>(string method, object arg, IScheduler scheduler)
        {
            var req = new AustinHarris.JsonRpc.JsonRequest()
            {
                Method = method,
                Params = new object[] { arg }
            };
            return InvokeRequestWithScheduler<T>(req, scheduler);
        }

        public IObservable<JsonResponse<T>> InvokeSingleArgument<T>(string method, object arg)
        {
            var req = new AustinHarris.JsonRpc.JsonRequest()
            {
                Method = method,
                Params = new object[] { arg }
            };
            return InvokeRequest<T>(req);
        }

        public IObservable<JsonResponse<T>> InvokeWithScheduler<T>(string method, object[] args, IScheduler scheduler)
        {
            var req = new AustinHarris.JsonRpc.JsonRequest()
            {
                Method = method,
                Params = args
            };
            return InvokeRequestWithScheduler<T>(req, scheduler);
        }

        public IObservable<JsonResponse<T>> Invoke<T>(string method, object[] args)
        {
            var req = new AustinHarris.JsonRpc.JsonRequest()
            {
                Method = method,
                Params = args
            };
            return InvokeRequest<T>(req);
        }

        public IObservable<JsonResponse<T>> InvokeRequestWithScheduler<T>(JsonRequest jsonRpc, IScheduler scheduler)
        {
            var res = Observable.Create<JsonResponse<T>>((obs) => 
                scheduler.Schedule(()=>{

                    makeRequest<T>(jsonRpc, obs);
                }));

            return res;
        }

        public IObservable<JsonResponse<T>> InvokeRequest<T>(JsonRequest jsonRpc)
        {
            return InvokeRequestWithScheduler<T>(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<T>(JsonRequest jsonRpc, IObserver<JsonResponse<T>> obs)
        {
            JsonResponse<T> 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<T>();
                }
                else
                {
                    sstream = sendAndReceive(json);
                    rjson = Newtonsoft.Json.JsonConvert.DeserializeObject<JsonResponse<T>>(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; }
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文