最近做一个和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的更多相关文章

  1. 測试JSON RPC远程调用(JSONclient)

    #include <string> #include <iostream> #include <curl/curl.h> /* 标题:JSonclient Auth ...

  2. go标准库的学习-net/rpc

    参考:https://studygolang.com/pkgdoc 导入方法: import "net/rpc" RPC(Remote Procedure Call Protoco ...

  3. go标准库的学习-net/rpc/jsonrpc

    参考:https://studygolang.com/pkgdoc 导入方式: import "net/rpc/jsonrpc" jsonrpc包实现了JSON-RPC的Clien ...

  4. go微服务框架go-micro深度学习(四) rpc方法调用过程详解

    上一篇帖子go微服务框架go-micro深度学习(三) Registry服务的注册和发现详细解释了go-micro是如何做服务注册和发现在,服务端注册server信息,client获取server的地 ...

  5. iOS学习——JSON数据解析(十一)

    在之前的<iOS学习——xml数据解析(九)>介绍了xml数据解析,这一篇简单介绍一下Json数据解析.JSON 即 JavaScript Object Natation,它是一种轻量级的 ...

  6. ajax学习----json,前后端交互,ajax

    json <script> var obj = {"name": "xiaopo","age": 18,"gender ...

  7. RabbitMQ学习之RPC(6)

    在第二个教程中,我们了解到如何在多个worker中使用Work Queues分发费时的任务. 但是,如果我们需要在远程运行一个函数并且等待结果该怎么办呢?这个时候,我们需要另外一个模式了.这种模式通常 ...

  8. android 学习JSON

    JSON的定义: 一种轻量级的数据交换格式,具有良好的可读和便于快速编写的特性.业内主流技术为其提供了完整的解决方案(有点类似于正则表达式 ,获得了当今大部分语言的支持),从而可以在不同平台间进行数据 ...

  9. SpringMVC学习--json

    简介 json数据格式在接口调用中.html页面中较常用,json格式比较简单,解析还比较方便.比如:webservice接口,传输json数据. springmvc与json交互 @RequestB ...

  10. iOS学习—JSON数据解析

      关于在iOS平台上进行JSON解析,已经有很多第三方的开源项目,比如TouchJson,JSONKit,SBJon等,自从iOS5.0以后,苹果SDK推出了自带的JSON解决方案NSJSONSer ...

随机推荐

  1. gustafson,Sun-Ni,Amdahl

    gustafson 定律由 John Gustafson首先提出.描述:系统优化某部件所获得的系统性能的改善程度,取决于该部件被使用的频率,或所占总执行时间的比例. Gustafson定理中,加速比与 ...

  2. Driver 初始化顺序

    Linux系统使用两种方式去加载系统中的模块:动态和静态. 静态加载:将所有模块的程序编译到Linux内核中,由do_initcall函数加载 核心进程(/init/main.c)kernel_ini ...

  3. Beginning Python From Novice to Professional (4) - 演示样本格式字符串

    $ gedit price.py #!/usr/bin/env python width = input('Please enter width: ') price_width = 10 item_w ...

  4. 该View转换成Bitmap方法

    方法一: /** * 该View绘制到Bitmap上 * @param view 须要绘制的View * @param width 该View的宽度 * @param height 该View的高度 ...

  5. SSL与TLS的区别以及介绍(转)

    SSL:(Secure Socket Layer,安全套接字层),位于可靠的面向连接的网络层协议和应用层协议之间的一种协议层.SSL通过互相认证.使用数字签名确保完整性.使用加密确保私密性,以实现客户 ...

  6. poj2942 Knights of the Round Table,无向图点双联通,二分图判定

    点击打开链接 无向图点双联通.二分图判定 <span style="font-size:18px;">#include <cstdio> #include ...

  7. 辛星解读为什么PHP须要模板

    近期有个人问我:为什么PHP须要模板呢?整个站点的编写都是我一个人完毕的,从前端到后端,都是这样,我一个人写站点是不是就不须要模板了呢?我当时还真给问住了,也没想好非常合适的回答它的方式,于是就随便说 ...

  8. coco2dx c++ HTTP实现

    coco2dx c++ HTTP实现 达到的结果如下面的 iPhone截图 android 日志截图 watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvdnBp ...

  9. kb3035583

    dism /online /Get-Packages /Format:Table|findstr 3035583 升级到w10补丁

  10. 教你如何使用U盘装系统

    首先,你必须有一个4G以上U菜,然后,U光盘制作软件(这里我们使用url=KRVS0FUdaNAMKPUXUxjEijxBMalUjaJHph-tL-x4gXGSwVNUW3fj6RfuZtrMg1Y ...