最近作一個和SmartHome相關的項目,文檔不全不說,連個像樣的Demo都沒,痛苦!!固然,這是題外話。今天來講說項目中主要用到的通信協議:json-rpc,簡單地說,它是以json格式進行的遠程調用,是一種比xml-rpc更lightweight的協議,具體的介紹可參考json-rpc官網和Wiki。這裏參考了Jayrock: JSON and JSON-RPC for .NET 也使用Jayrock來講說json-rpc的應用。javascript
首先,添加引用,先經過Nuget獲取Json.net,而後引用Jayrock.dll和Jayrock.Json.dllhtml
創建一些Model,這個根據實際狀況來建立。我這裏服務器用戶登陸須要的json的格式,例如:java
{"method":"Login","params":{"username":"test2014","password":"test2014"}}
咱們這裏建立這麼幾個實體:spring
#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
建立HtmlPage1.html頁面:json
<!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); } } } }
運行結果:session