学习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
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, , 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 == "" ? 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, , 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);
}
}
}
}
运行结果:

学习json-rpc的更多相关文章
- 測试JSON RPC远程调用(JSONclient)
#include <string> #include <iostream> #include <curl/curl.h> /* 标题:JSonclient Auth ...
- go标准库的学习-net/rpc
参考:https://studygolang.com/pkgdoc 导入方法: import "net/rpc" RPC(Remote Procedure Call Protoco ...
- go标准库的学习-net/rpc/jsonrpc
参考:https://studygolang.com/pkgdoc 导入方式: import "net/rpc/jsonrpc" jsonrpc包实现了JSON-RPC的Clien ...
- go微服务框架go-micro深度学习(四) rpc方法调用过程详解
上一篇帖子go微服务框架go-micro深度学习(三) Registry服务的注册和发现详细解释了go-micro是如何做服务注册和发现在,服务端注册server信息,client获取server的地 ...
- iOS学习——JSON数据解析(十一)
在之前的<iOS学习——xml数据解析(九)>介绍了xml数据解析,这一篇简单介绍一下Json数据解析.JSON 即 JavaScript Object Natation,它是一种轻量级的 ...
- ajax学习----json,前后端交互,ajax
json <script> var obj = {"name": "xiaopo","age": 18,"gender ...
- RabbitMQ学习之RPC(6)
在第二个教程中,我们了解到如何在多个worker中使用Work Queues分发费时的任务. 但是,如果我们需要在远程运行一个函数并且等待结果该怎么办呢?这个时候,我们需要另外一个模式了.这种模式通常 ...
- android 学习JSON
JSON的定义: 一种轻量级的数据交换格式,具有良好的可读和便于快速编写的特性.业内主流技术为其提供了完整的解决方案(有点类似于正则表达式 ,获得了当今大部分语言的支持),从而可以在不同平台间进行数据 ...
- SpringMVC学习--json
简介 json数据格式在接口调用中.html页面中较常用,json格式比较简单,解析还比较方便.比如:webservice接口,传输json数据. springmvc与json交互 @RequestB ...
- iOS学习—JSON数据解析
关于在iOS平台上进行JSON解析,已经有很多第三方的开源项目,比如TouchJson,JSONKit,SBJon等,自从iOS5.0以后,苹果SDK推出了自带的JSON解决方案NSJSONSer ...
随机推荐
- 获得树形json串
public class TreeNode { private long nodeId; private String nodeName; private long fatherNod ...
- maven仓库总结,maven私服搭建
配置pom.xml依赖包时在这里找包的描述: http://search.maven.org/#browse 以java为根目录. mvn archtype:generate -DgroupId=zt ...
- c#和UDP SOCKET广播
server: Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram,ProtocolType.Udp); // ...
- 关于Hbase的cache配置
关于Hbase的cache配置 在hbase中的hfilecache中,0.96版本号中新添加了bucket cache, bucket cache通过把hbase.offheapcache.perc ...
- Android系统各版本号及代号
Android系统各版本号及代号 版本 版本号代号 公布日期 API Android 1.0 阿童木 1 Android 1.1 发条机器人 2008.9 2 Android 1.5 纸杯蛋糕 200 ...
- [Oracle] 接线表
于OLTP制,嵌套连接占70%左右,哈希联接占20%,合并排序连接帐户10%. 嵌套连接 算法:嵌套连接从两个表分选出小表为驱动表,大表为被驱动表.先訪问驱动表(仅仅訪问1次).然后依据驱动表返回的行 ...
- 熬之滴水穿石:Spring--精简的J2EE(6)
48--曾用过的View 在Spring MVC架构中View实际上是有多种选择的.JSP是首选的view,实际上在J2E ...
- Android实现隐藏状态栏和标题栏
隐藏标题栏需要使用预定义样式:android:theme=”@android:style/Theme.NoTitleBar”. 隐藏状态栏:android:theme=”@android:style/ ...
- hdu3501
要我们求小于n并且不与n互素的数字的和, 那么可以转化为1->(n-1)的和减去小于n且与n互素的数字的和 首先,有gcd(n,i)=1, 那么gcd(n,n-i)=1, 这是因为如果a%s=0 ...
- slider使用TickPlacement获得游标效果
<Slider Name="slider游标效果" Maximum="3" SmallChange="0.25" TickPlacem ...