本博文主要介绍JSON以及JSONRPC的使用
RPC的原理和设计框架
JSON
JavaScriptObject Notation, 是一种轻量级的数据交换格式,它采用完全独立于语言的文本格式,成为一种理想的数据交换语言。
基础结构:
对象和数组,通过这两种结构可以表示各种复杂的结
语法:
数据在名称/值对中;数据由逗号分隔;花括号保存对象;方括号保存数组
与XML的比较:
1. 可读性:不相上下
2. 可扩展性:不相上下,但是json在javascript上拥有天生的优势
3. 编码:不相上下,但是json编码出来的长度比xml少
4. 解码:xml第一种是预先知道文档结构则通过文档模型解析,第二种是遍历节点;json预知json结构解析起来非常方便,但是不知json结构解析起来非常痛苦。
5. 可读性:xml适合人类读,json适合机器读
实例:
{
"jsonrpc": "2.0", "method": "get", "params": {"param1": "hello" }, "id": 1,"messages":[1,2]
}
json的编码和解码会在另外的章节描述,这里只描述JSONRPC过程,以下程序使用TCP socket作为传输机制:
一:jar包
二:方法类(与XMLRPC一样)
public interface Calculator {
public int add(int i, intj);
public int subtract(int i, intj);
}
public classCalculatorImpl implements Calculator{
public int add(int i, int j){
return i +j;
}
public intsubtract(int i, int j) {
return i -j;
}
}
三:服务端
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
importjava.net.UnknownHostException;
importjavax.net.ServerSocketFactory;
importcom.googlecode.jsonrpc4j.JsonRpcServer;
importcom.googlecode.jsonrpc4j.StreamServer;
public class JosnRPCSocketServer{
public static void main(String[] args) throwsUnknownHostException,IOException{
ServerSocket serverSocket =ServerSocketFactory.getDefault().createServerSocket(4444, 50,InetAddress.getByName("127.0.0.1"));//创建socketServerCalculatorImpl cal = newCalculatorImpl();//创建服务过程对象JsonRpcServer jsonRpcServer = newJsonRpcServer(cal,Calculator.class);//把服务过程对象放入RpcServer中StreamServer streamServer = newStreamServer(jsonRpcServer, 5,serverSocket);//设置存根过程,并把通信模块和服务过程与之相连streamServer.start();//启动服务
}
}
四:客户端
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
importjava.net.UnknownHostException;
importcom.googlecode.jsonrpc4j.JsonRpcClient;
importcom.googlecode.jsonrpc4j.ProxyUtil;
public class JosnRPCSocketClient{
public void get() throws UnknownHostException,IOException {
Socket socket = newSocket(InetAddress.getByName("127.0.0.1"),4444);//建立socket连接JsonRpcClient jsonRpcClient = newJsonRpcClient();//创建RpcClient,建立存根过程Calculator cal =ProxyUtil.createClientProxy(this.getClass().getClassLoader(), Calculator.class,jsonRpcClient, socket);//连接通信模块、存根服务和客户程序System.out.println(cal.add(1,2));System.out.println(cal.subtract(1,2));socket.close();}
public static void main(String[] args) throwsUnknownHostException,IOException{JosnRPCSocketClient jrsc = newJosnRPCSocketClient();jrsc.get();
}
}
由于博主知识有限,如有误,请指正点评,欢迎交流