在上一篇文章《手把手教你写rpc框架系列(十)定义网络通信模块的二进制协议》中,我们定义了二进制的通信协议,但是在这个MessageProtocol类里面看到他只是一个接口,是没有实现的,因此这里我们需要来实现下这个通信协议的接口。
说到这里的实现,其实业务比较简单,主要是对编组和解组消息进行序列化和反序列化,因此这里我们实现下二进制通信协议的java序列化和反序列化。
首先创建一个JavaSerializeMessageProtocol的类,实现MessageProtocol这个接口。代码如下:
public class JavaSerializeMessageProtocol implements MessageProtocol { /** * 编组请求 * * @param req 请求信息 * @return 请求字节数组 * @throws Exception 编组请求异常 */ byte[] marshallingRequest(MessageRequest req) throws Exception; /** * 解组请求 * * @param data 请求字节数组 * @return 请求信息 * @throws Exception 解组请求异常 */ MessageRequest unmarshallingRequest(byte[] data) throws Exception; /** * 编组响应 * * @param rsp 响应信息 * @return 响应字节数组 * @throws Exception 编组响应异常 */ byte[] marshallingResponse(MessageResponse rsp) throws Exception; /** * 解组响应 * * @param data 响应字节数组 * @return 响应信息 * @throws Exception 解组响应异常 */ MessageResponse unmarshallingResponse(byte[] data) throws Exception; }
这里的话,我们首先编写一个序列化的公共方法,完整代码如下:
/** * 序列化 * @param obj * @return * @throws Exception */ private byte[] serialize(Object obj) throws Exception { ByteArrayOutputStream bout = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(bout); out.writeObject(obj); return bout.toByteArray(); }
然后再编写一个反序列化的公共方法,完整代码如下:
/** * 反序列化 * @param data * @return * @throws Exception */ private Object unSerialize(byte[] data) throws Exception { ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(data)); return (MessageRequest) in.readObject(); }
最后我们来实现编组请求,解组请求,编组响应,解组响应这几个方法,其实很简单,就是把这个序列化和反序列化套进去即可,如下图:
这样子我们就实现了一个通信协议的java序列化和反序列化。目前的项目结构如下:
备注:
1、这里的反序列化我们编写优点问题,源码代码是:
private Object unSerialize(byte[] data) throws Exception { ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(data)); return (MessageRequest) in.readObject(); }
需要纠正下,纠正成:
private Object unSerialize(byte[] data) throws Exception { ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(data)); return in.readObject(); }
还没有评论,来说两句吧...