netty 权威指南 第二版 MessagePack demo

最近在看netty 权威指南 第二版的书,坑得是运行事例时老是不能走通,网上想找第七章的源码,一个个都是积分,还是第一版的!其实demo很简单,就是有个坑,不注意,可能就是凉凉了,不深入debug,不知道有没有一次走通的?反正 我是郁闷了好久。

废话少说,上代码无组织无纪律,如果有缺少的类,以你们的能力自己补上,看不上的不要喷:(maven工程)

    
      io.netty
      netty-all
      5.0.0.Alpha2
    
    
      org.msgpack
      msgpack
      0.6.12
    

codec相关:

public class MessagePackDecoder extends MessageToMessageDecoder {
    @Override
    protected void decode(ChannelHandlerContext arg0, ByteBuf arg1, List arg2) throws Exception {
        final byte[] array;
        final int length = arg1.readableBytes();
        array = new byte[length];
        System.out.println("MessagePackDecoder==》" + arg1);
        arg1.getBytes(arg1.readerIndex(),array,0,length);
        MessagePack msgpack = new MessagePack();

        arg2.add(msgpack.read(array));

    }
} 
  

 

public class MessagePackEncoder extends MessageToByteEncoder {
    @Override
    protected void encode(ChannelHandlerContext arg0, Object o, ByteBuf byteBuf) throws Exception {
        System.out.println("MessagePackEncoder ==》" + o);
        MessagePack msgpack = new MessagePack();
        byte[] raw = msgpack.write(o);
        byteBuf.writeBytes(Unpooled.copiedBuffer(raw));
        arg0.flush();
    }
} 
  

handler相关:

public class EchoClientHandler extends ChannelHandlerAdapter {
    private final int sendNumber;

    public EchoClientHandler(int sendNumber) {
        this.sendNumber = sendNumber;
    }

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

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        UserInfo[] infos = UserInfo();
        for(UserInfo infoE:infos){
            ctx.writeAndFlush(infoE);
        }
        ctx.flush();
    }

    private UserInfo[] UserInfo(){
        UserInfo[] infos = new UserInfo[sendNumber];
        UserInfo user = null;
        for(int i=0; i"+i);
            infos[i] = user;
        }
        return infos;
    }
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("Client receive the msgpack message:"+msg );
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

    @Override
    public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
        System.out.println("write");
        super.write(ctx, msg, promise);
    }
}

 

public class EchoServerHandler extends ChannelHandlerAdapter {
    int counter = 0;
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("This is " + (++counter)+" times receive client:[" + msg +"]");
        ctx.writeAndFlush(msg);
    }
}

最坑的就是这个UserInfo,@Message 这个注解一定要加上,不然server端收不到消息,我运行时是出现这样的问题,如果没有遇到这样的问题那你很幸运,其他的就很简单

@Message 
public class UserInfo {
    private int age;
    private String name;

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "[" +age+
                ","  + name +
                ']';
    }
}

 

服务端EchoServer

public class EchoServer {
    public void bind(int port) throws Exception{
        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)
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .childHandler(new ChannelInitializer() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast("frameDecoder",new LengthFieldBasedFrameDecoder(65535,0,2,0,2));
                            ch.pipeline().addLast("msgpack decoder",new MessagePackDecoder());
                            ch.pipeline().addLast("frameEncoder",new LengthFieldPrepender(2));
                            ch.pipeline().addLast("msgpack encoder",new MessagePackEncoder());
                            ch.pipeline().addLast(new EchoServerHandler());
                        }
                    });
            ChannelFuture f = b.bind(port).sync();
            f.channel().closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }


    public static void main(String[] args) throws Exception{
        int port = 8080;
        new EchoServer().bind(port);
    }
}

 

客户端 EchoClient

public class EchoClient {
    public void connect(int port, String host)throws Exception{
        EventLoopGroup group = new NioEventLoopGroup();
       try{
           Bootstrap b = new Bootstrap();
           b.group(group).channel(NioSocketChannel.class)
                   .option(ChannelOption.TCP_NODELAY,true)
                   .option(ChannelOption.CONNECT_TIMEOUT_MILLIS,3000)
                   .handler(new ChannelInitializer() {
               @Override
               protected void initChannel(SocketChannel ch) throws Exception {
                   ch.pipeline().addLast("frameDecoder",new LengthFieldBasedFrameDecoder(65535,0,2,0,2));
                   ch.pipeline().addLast("msgpack decoder",new MessagePackDecoder());
                   ch.pipeline().addLast("frameEncoder",new LengthFieldPrepender(2));
                   ch.pipeline().addLast("msgpack encoder",new MessagePackEncoder());
                   ch.pipeline().addLast(new EchoClientHandler(10));
               }
           });
           ChannelFuture f = b.connect(host,port).sync();
           f.channel().closeFuture().sync();
       }finally {
            group.shutdownGracefully();
       }

    }

    public static void main(String[] args) throws Exception {
        int port = 8080;
        new EchoClient().connect(port,"127.0.0.1");
    }
}

好运!

你可能感兴趣的:(netty,MessagePack,源码)