Netty-Marshalling编解码

本文介绍如何使用JBoss Marshalling实现消息的编码与解码。通过创建MarshallingFactory,提供MarshallingDecoder和MarshallingEncoder的具体实现。适用于服务器与客户端之间的信息通讯。

和前面的不同,采用jboss-marshalling进行编解码,优先创建一个编解码的工厂类,供信息通讯时候对信息的编解码

import org.jboss.marshalling.MarshallerFactory;
import org.jboss.marshalling.Marshalling;
import org.jboss.marshalling.MarshallingConfiguration;
import io.netty.handler.codec.marshalling.DefaultMarshallerProvider;
import io.netty.handler.codec.marshalling.DefaultUnmarshallerProvider;
import io.netty.handler.codec.marshalling.MarshallerProvider;
import io.netty.handler.codec.marshalling.MarshallingDecoder;
import io.netty.handler.codec.marshalling.MarshallingEncoder;
import io.netty.handler.codec.marshalling.UnmarshallerProvider;
/**
 * @FileName MarshallingFactory.java
 * @Description: 处理通讯中消息的编解码
 *
 * @Date 2016年3月7日 
 * @author Administroter
 * @version 1.0
 * 
 */
public final class MarshallingFactory {
 /**
  * @Title: createMarshallingDecoder 
  * @Description:创建Marshalling解码器
  * @return 
  * @author Administroter
  * @date 2016年3月7日
  */
 public static MarshallingDecoder createMarshallingDecoder(){
  //实例化java序列化MarshallingFactory工厂,其中参数serial表示的就是java版的
  final MarshallerFactory mf = Marshalling.getProvidedMarshallerFactory("serial");
  final MarshallingConfiguration mc = new MarshallingConfiguration();
  mc.setVersion(5);
  UnmarshallerProvider up = new DefaultUnmarshallerProvider(mf, mc);
  //这里面的1024表示的是单个消息序列化后的最大长度
  MarshallingDecoder decoder =  new MarshallingDecoder(up,1024);
  return decoder;
 }
 /**
  * @Title: createMarshallingEncoder 
  * @Description:创建Marshalling编码器
  * @return 
  * @author Administroter
  * @date 2016年3月7日
  */
 public static MarshallingEncoder createMarshallingEncoder(){
  final MarshallerFactory mf = Marshalling.getProvidedMarshallerFactory("serial");
  final MarshallingConfiguration mc = new MarshallingConfiguration();
  mc.setVersion(5);
  MarshallerProvider up = new DefaultMarshallerProvider(mf, mc);
  //对象序列化成二进制数组
  MarshallingEncoder me = new MarshallingEncoder(up);
  return me;
 }
}

服务器端和客户端和前面的protobuf一样的,只需要更改下编解码就OK了

173435_RkJx_2336827.png

转载于:https://my.oschina.net/673236963/blog/632262

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值