最近做一个和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. getline与get函数的区别

    get()函数相对getline来说使用方法要灵活的多了. 1.   int get()是指从流中抽取单个字符并返回,这个是没有參数的形式.由于c++不像c语言使用getchar() 2.istrea ...

  2. IIS架构与HTTP请求处理流程

    IIS架构与HTTP请求处理流程 Windows操作系统中的IIS负责提供互联网服务,一台运行了IIS的计算机可以看成是一台Web服务器. Windows XP SP2 中IIS主版本号为5,Wind ...

  3. Base64实现android端图片上传到server端

    首先要下载Base64.java文件http://iharder.sourceforge.net/current/java/base64/ 将代码复制到project中. 然后上代码: android ...

  4. WPF换肤之八:创建3D浏览效果

    原文:WPF换肤之八:创建3D浏览效果 上节中,我们展示了WPF中的异步以及界面线程交互的方式,使得应用程序的显示更加的流畅.这节我们主要讲解如何设计一个具有3D浏览效果的天气信息浏览器. 效果显示 ...

  5. Linux下多线程查看工具(pstree、ps、pstack) (转)

    1. pstree pstree以树结构显示进程$ pstree -p work | grep adsshd(22669)---bash(22670)---ad_preprocess(4551)-+- ...

  6. wordpress博客近期变慢之解决(fonts.google.com)

    近期发现站点訪问速度变慢.博客文章打开速度特慢,也没改动过东西. 并且近期发现google的服务非常多訪问都打不开或是变慢. 于是知道可能是那"伟大东西"在作坏事了. 症状: 网页 ...

  7. mysql寻呼最快

    大家都知道,mysql分页写: select * from 'yourtable' limit start,rows 如今我数据库一张表里面有9969W条数据.表名叫tweet_data select ...

  8. IOS加强知识(1)理解力Objective-C

    一直想写一般Objective-C帖子,总是没时间.所以,我希望有一个巨大的知识更小.温馨提示小的变化.写一点点,每天.东西把他们的学习分享,好了废话不多. 1.一门动态的语言OC Object-C( ...

  9. SQL注入问题

    斌斌 (给我写信) 原创博文(http://blog.csdn.net/binbinxyz),转载请注明出处! 背景:对于ibaits参数引用可以使用#和$两种写法,其中#写法会采用预编译方式,将转义 ...

  10. 询url包括字符串参数(js高度注意事项)

    以防万一  url="http://write.blog.csdn.net/postedit? id=5&search=ok" function getArgs() { v ...