最近做一个和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. cocos2d-x 旅程開始--(实现瓦片地图中的碰撞检測)

    转眼隔了一天了,昨天搞了整整一下午加一晚上,楞是没搞定小坦克跟砖头的碰撞检測,带着个问题睡觉甚是难受啊!还好今天弄成功了.只是感觉程序不怎么稳定啊.并且发现自己写的东西让我重写一遍的话我肯定写不出来. ...

  2. nginx学习12 ngx_cycle_t 和 ngx_init_cycle

    在nginx在启动过程,ngx_init_cycle这个函数最初始工作.变量的初始化存储在ngx_cycle_t这个结构体中,为了深入了解这个函数都做了那些初始化工作,就化时间研究了一下.并写下来以便 ...

  3. linux操作提示:“Can&#39;t open file for writing”或“operation not permitted”的解决的方法

    在linux上使用vi命令改动一个文件内容的时候,发现无法保存,每次写完使用":q!"命令能够正常退出可是使用":wq!"命令保存文件并退出时出现一下信息提示: ...

  4. Java EE (11) - 影响性能的因素

    垂直层(Tier)影响性能的因素 资源层数据库性能通常考虑以下方面的优化(MySQL为例):--使用哪种存储引擎:MyISAM vs. InnoDB, MERGE, MEMORY, Federated ...

  5. 使用Sublime Text 2编辑和运行node-webkit应用程序

    开发工具目录结构 --E:\develop\ ----node-webkit-v0.9.2-win-ia32 ----Sublime Text 2.0.2 x64 为Sublime text2构建Bu ...

  6. windows phone 获取手机图片库中图片(4)

    原文:windows phone 获取手机图片库中图片(4) 前置条件:手机和电脑未连接或连接电脑Zune软件关闭(与Zune软件连接时不允许访问图片库): 版本7.1 获取手机图片库图片的两种方式: ...

  7. Leet code —Jump Game

    问题叙述性说明: Given an array of non-negative integers, you are initially positioned at the first index of ...

  8. 13-7-5 android Tabhost功能实现

    开始使用了一个Activity做界面切换,采用visible.gone写法,感觉太麻烦了. layoutHousehold.setVisibility(View.GONE); layoutCamera ...

  9. hihocoder第41周 骨牌覆盖(矩阵快速幂)

    由于棋盘只有两行,所以如果第i列的骨牌竖着放,那么就转移为第1列到第i-1列骨牌有多少种摆法 如果第一行第i列骨牌横着放,那么第二行第i列也要横着放,那么就转移为了第1列到第i-2列骨牌有多少种方法 ...

  10. uva103(最长递增序列,dag上的最长路)

    题目的意思是给定k个盒子,每个盒子的维度有n dimension 问最多有多少个盒子能够依次嵌套 但是这个嵌套的规则有点特殊,两个盒子,D = (d1,d2,...dn) ,E = (e1,e2... ...