zoukankan      html  css  js  c++  java
  • 学习json-rpc

    最近做一个和SmartHome相关的项目,文档不全不说,连个像样的Demo都没,痛苦!!当然,这是题外话。今天来说说项目中主要用到的通讯协议:json-rpc,简单地说,它是以json格式进行的远程调用,是一种比xml-rpc更lightweight的协议,具体的介绍可参考json-rpc官网Wiki。这里参考了Jayrock: JSON and JSON-RPC for .NET 也使用Jayrock来说说json-rpc的应用。

    1.准备工作

    首先,添加引用,先通过Nuget获取Json.net,然后引用Jayrock.dll和Jayrock.Json.dll

    建立一些Model,这个根据实际情况来创建。我这里服务器用户登录需要的json的格式,例如:

    {"method":"Login","params":{"username":"test2014","password":"test2014"}}

    我们这里创建这么几个实体:

    #region Login
        public class LoginModel
        {
            public string method { get; set; }
            public LoginParams _params { get; set; }
        }
        public class LoginParams
        {
            public string username { get; set; }
            public string password { get; set; }
        }
        public class LoginReturnModel
        {
            public string result { get; set; }
            public string info { get; set; }
        } 
        #endregion
    
        #region GetDeviceInfo
        public class GetDeviceInfoModel
        {
            public string method { get; set; }
            public GetDeviceInfoParams _params { get; set; }
        }
        public class GetDeviceInfoParams
        {
    
        }
        public class GetDeviceInfoReturnModel
        {
            public string result { get; set; }
            public GetDiveInfoReturnInfo[] info { get; set; }
        }
        public class GetDiveInfoReturnInfo
        {
            public string deviceid { get; set; }
            public string deviceno { get; set; }
            public string identify { get; set; }
            public string lable { get; set; }
        } 
        #endregion
    View Code

    2.准备页面和处理程序

    创建HtmlPage1.html页面:

    <!DOCTYPE html>
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
        <title></title>
        <script src="js/json.js"></script>
        <script type="text/javascript" src="Handler.ashx?proxy"></script>
        <script type="text/javascript">
            window.onload = function () {
                var s = new Handler();
                s.Login('test2014@99guard.com', 'test2014');
                alert(s.GetDeviceInfo());
            }
        </script>
    </head>
    <body>
    
    </body>
    </html>

    创建Handler.ashx:

    using Jayrock.JsonRpc;
    using Jayrock.JsonRpc.Web;
    using Newtonsoft.Json;
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Net;
    using System.Text;
    using System.Web;
    
    namespace JsonRpcTest3
    {
        /// <summary>
        /// Handler 的摘要说明
        /// </summary>
        public class Handler : JsonRpcHandler
        {
            string requestUri;
            string requestMethod;
            string contentType;
            public Handler()
            {
                requestUri = "http://u.99guard.com:8080/homehand_spring_6/ziga8/usss.do";
                requestMethod = "POST";
                contentType = "application/json-rpc";
            }
            [JsonRpcMethod(Name="Login")]
            public bool Login(string username, string password)
            {
                string result;
                LoginParams lp = new LoginParams();
                lp.username = username;
                lp.password = password;
                LoginModel lm = new LoginModel();
                lm.method = "Login";
                lm._params = lp;
                string jsonData = JsonConvert.SerializeObject(lm).Replace("_params", "params");
                byte[] bytes = Encoding.UTF8.GetBytes(jsonData+" ");
                HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(requestUri);
                request.Method = requestMethod;
                request.ContentType = contentType;
                request.ContentLength = bytes.Length;
                Stream requestStream = request.GetRequestStream();
                requestStream.Write(bytes, 0, bytes.Length);
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                using (Stream s = response.GetResponseStream())
                {
                    using (StreamReader sr = new StreamReader(s,Encoding.UTF8))
                    {
                        result = sr.ReadToEnd();
                    }
                }
                LoginReturnModel lrm = JsonConvert.DeserializeObject<LoginReturnModel>(result);
                bool status = lrm.result == "0" ? true : false;
                if (status)
                {
                    StoreSession(response.Headers["Set-Cookie"]);
                }
                return status;
            }
    
            [JsonRpcMethod(Name = "GetDeviceInfo")]
            public string GetDeviceInfo()
            {
                string sessonId = File.ReadAllText(@"d:1.txt");
                string result;
                GetDeviceInfoModel model = new GetDeviceInfoModel();
                model.method = "GetDeviceInfo";
                model._params = new GetDeviceInfoParams();
                string jsonData = JsonConvert.SerializeObject(model).Replace("_params", "params");
                byte[] bytes = Encoding.UTF8.GetBytes(jsonData + " ");
                HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(requestUri);
                request.Method = requestMethod;
                request.ContentType = contentType;
                request.ContentLength = bytes.Length;
                request.Headers.Add("Cookie", sessonId);
                Stream requestStream = request.GetRequestStream();
                requestStream.Write(bytes, 0, bytes.Length);
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                using (Stream s = response.GetResponseStream())
                {
                    using (StreamReader sr = new StreamReader(s, Encoding.UTF8))
                    {
                        result = sr.ReadToEnd();
                    }
                }
                GetDeviceInfoReturnModel returnModel = JsonConvert.DeserializeObject<GetDeviceInfoReturnModel>(result);
                return JsonConvert.SerializeObject(returnModel);
            }
    
            public void StoreSession(string session)
            {
                if (!string.IsNullOrEmpty(session))
                {
                    File.WriteAllText(@"d:1.txt", session);
                }
            }
        }
    }

    运行结果:

  • 相关阅读:
    Naive Operations HDU6315 (杭电多校2G)
    Baker Vai LightOJ
    LOJ#6278. 数列分块入门 2
    LOJ#6277. 数列分块入门 1
    Picture POJ
    Who Gets the Most Candies? POJ
    Dividing the Path POJ
    Balanced Sequence HDU
    归并排序
    Flying to the Mars
  • 原文地址:https://www.cnblogs.com/jellochen/p/3821340.html
Copyright © 2011-2022 走看看