JBoss Marshalling编解码的学习

1.首先交代maven依赖Marshalling API 和Marshalling Serial Protocol

<!-- https://mvnrepository.com/artifact/org.jboss.marshalling/jboss-marshalling -->
<dependency>
    <groupId>org.jboss.marshalling</groupId>
    <artifactId>jboss-marshalling</artifactId>
    <version>2.0.2.Final</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.jboss.marshalling/jboss-marshalling-serial -->
<dependency>
    <groupId>org.jboss.marshalling</groupId>
    <artifactId>jboss-marshalling-serial</artifactId>
    <version>2.0.2.Final</version>
    <scope>test</scope>
</dependency>

2.

package com.test.frame.zookeeper.marshalling;

import io.netty.handler.codec.marshalling.*;
import org.jboss.marshalling.MarshallerFactory;
import org.jboss.marshalling.Marshalling;
import org.jboss.marshalling.MarshallingConfiguration;

/**
 * MarshallingCodeFactory class
 *
 * @author guanhuifang
 * @date 2017/10/31 下午2:45
 **/
public final class MarshallingCodeFactory {





    /**
     * 创建Marshalling解码器MarshallingDecoder
     * @return
     */
    public static MarshallingDecoder  buildMarshallingDecoder(){
        /**
         * 利用Marshalling工具类的静态方法getProvidedMarshallerFactory获取MarshallerFactory实例
         */
        final MarshallerFactory marshallerFactory = Marshalling.getProvidedMarshallerFactory("serial");
        /**
         * 创建MarshallingConfiguration对象,设置其版本为5
         */
        final MarshallingConfiguration configuration = new MarshallingConfiguration();
        configuration.setVersion(5);
        /**
         * 创建UnmarshallerProvider实例
         */
        UnmarshallerProvider provider=new DefaultUnmarshallerProvider(marshallerFactory,configuration);
        /**
         * 通过构造函数创建Netty的MarshallingDecoder对象,参数为UnmarshallerProvider和单个消息序列化后的最大长度
         */
        MarshallingDecoder  decoder = new MarshallingDecoder(provider,1024);
        return decoder;
    }



    public static MarshallingEncoder buildMarshallingEncoder(){
        final MarshallerFactory marshallerFactory = Marshalling.getProvidedMarshallerFactory("serial");
        final MarshallingConfiguration configuration = new MarshallingConfiguration();
        configuration.setVersion(5);
        /**
         * 创建MarshallerProvider对象
         */
        MarshallerProvider provider = new DefaultMarshallerProvider(marshallerFactory,configuration);
        /**
         * MarshallingEncoder用于将实现序列化接口的pojo对象序列化为二进制数组
         */
        MarshallingEncoder encoder =new MarshallingEncoder(provider);
        return encoder;
    }
}

3.服务端开发

package com.test.frame.zookeeper.marshalling;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * SubReqServer class
 *
 * @author guanhuifang
 * @date 2017/10/31 下午2:32
 **/
public class SubReqServer {


    public void bind(int port) throws InterruptedException {

        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 100)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(MarshallingCodeFactory.buildMarshallingDecoder());
                            ch.pipeline().addLast(MarshallingCodeFactory.buildMarshallingEncoder());
                            ch.pipeline().addLast(new SubReqServerHandler());
                        }
                    });


            ChannelFuture f = b.bind(port).sync();
            f.channel().closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }

    }


    public static void main(String[] args) throws InterruptedException {
        new SubReqServer().bind(8080);
    }
}

 

package com.test.frame.zookeeper.marshalling;

import com.test.frame.zookeeper.pojo.SubscribeReq;
import com.test.frame.zookeeper.pojo.SubscribeResp;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

/**
 * SubReqServerHandler class
 *
 * @author guanhuifang
 * @date 2017/10/31 下午2:35
 **/
public class SubReqServerHandler extends ChannelInboundHandlerAdapter {


    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg){

        SubscribeReq req = (SubscribeReq) msg;
        System.out.println("服务端收到消息体:"+req.toString());
        if("gholly".equalsIgnoreCase(req.getUserName())){
            ctx.writeAndFlush(subResp(req.getSubReqID()));
        }



    }



    private SubscribeResp subResp(int i){
        SubscribeResp resp =new SubscribeResp();
        resp.setSubReqID(i);
        resp.setRespCode(0);
        resp.setDesc("I love China");
        return resp;
    }



    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause){
        ctx.close();
    }
}

4.客户端开发

package com.test.frame.zookeeper.marshalling;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

/**
 * SubReqClient class
 *
 * @author guanhuifang
 * @date 2017/10/31 下午2:38
 **/
public class SubReqClient {


    public void connect(String host, int port) throws InterruptedException {

        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.TCP_NODELAY, true)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(MarshallingCodeFactory.buildMarshallingDecoder());
                            ch.pipeline().addLast(MarshallingCodeFactory.buildMarshallingEncoder());
                            ch.pipeline().addLast(new SubReqClientHandler());
                        }
                    });


            ChannelFuture f = b.connect(host, port).sync();
            f.channel().closeFuture().sync();
        } finally {
            group.shutdownGracefully();
        }

    }


    public static void main(String[] args) throws InterruptedException {
        new SubReqClient().connect("127.0.0.1",8080);
    }
}

 

package com.test.frame.zookeeper.marshalling;

import com.test.frame.zookeeper.pojo.SubscribeReq;
import com.test.frame.zookeeper.pojo.SubscribeResp;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

/**
 * SubReqClientHandler class
 *
 * @author guanhuifang
 * @date 2017/10/31 下午2:41
 **/
public class SubReqClientHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg){

        System.out.println(msg);
        SubscribeResp resp = (SubscribeResp) msg;
        System.out.println("客户端收到消息体为:"+resp.toString());
    }


    private SubscribeReq subReq(int i){
        SubscribeReq req= new SubscribeReq();
        req.setAddress("Shenzhen");
        req.setPhoneNumber("110");
        req.setProductName("netty");
        req.setSubReqID(i);
        req.setUserName("gholly");
        return req;
    }



    @Override
    public void channelActive(ChannelHandlerContext ctx){
        for(int i=0;i<10;i++){
            ctx.write(subReq(i));
        }
        ctx.flush();

    }


    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause){
        ctx.close();
    }
}

运行结果:

164756_EIne_2263272.png

netty的Marshalling编解码器支持半包粘包的处理

 

转载于:https://my.oschina.net/u/2263272/blog/1558836

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值