netty使用messagepack编解码

91 阅读1分钟

定义需要编解码的User类

需要使用@Message注解


package io.netty.example.messagepack;

import org.msgpack.annotation.Message;
import org.msgpack.template.FieldOption;

@Message(value = FieldOption.DEFAULT)
public class User {
    private Integer id;
    private String name;

    public User(){

    }

    public User(Integer id, String name) {
        this.id = id;
        this.name = name;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + ''' +
                '}';
    }
}

定义编码handler

客户端编码handler

package io.netty.example.messagepack;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import org.msgpack.MessagePack;

public class MsgEncodeHandler extends MessageToByteEncoder {

    @Override
    protected void encode(ChannelHandlerContext ctx, Object msg, ByteBuf out) throws Exception {
        MessagePack messagePack = new MessagePack();
        byte[] write = messagePack.write(msg);
        out.writeBytes(write);
    }
}

发送消息handler

package io.netty.example.messagepack;

import io.netty.channel.*;

public class ClientHandler extends ChannelInboundHandlerAdapter {
    public ClientHandler(){

    }
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("active");
        User hello = new User(1, "hello");
        ctx.write(hello).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                System.out.println("future result: " + future.get());
            }
        });
        ctx.flush();
    }
}

定义服务端handler

服务端解码handler

package io.netty.example.messagepack;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import org.msgpack.MessagePack;
import org.msgpack.type.Value;

import java.util.List;

public class MsgDecodeHandler extends ByteToMessageDecoder {
    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        System.out.println("decode....");
        int length = in.readableBytes();
        final byte[] bytes = new byte[length];
        in.getBytes(in.readerIndex(), bytes, 0, length);
        MessagePack messagePack = new MessagePack();
        Value read = messagePack.read(bytes);
        System.out.println(read);
        out.add(read);
    }
}

服务端打印User对象

package io.netty.example.messagepack;

import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandlerContext;
import org.msgpack.type.ArrayValue;
import org.msgpack.type.Value;

public class MsgHandler extends ChannelDuplexHandler {
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ArrayValue value = (ArrayValue) msg;
        Value[] elementArray = value.getElementArray();
        User user = new User(elementArray[0].asIntegerValue().getInt(), elementArray[1].asRawValue().getString());
        System.out.println(user.toString());

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("except: " + cause.toString());

    }
}

客户端

package io.netty.example.messagepack;

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

public class Client {
    public static void main(String[] args) throws InterruptedException {
        NioEventLoopGroup work = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.channel(NioSocketChannel.class)
                .group(work)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast("msgEncode", new MsgEncodeHandler());
                        ch.pipeline().addLast(new ClientHandler());
                    }
                });
        ChannelFuture localhost = bootstrap.connect("localhost", 9998);

        localhost.await();


    }
}

服务端

package io.netty.example.messagepack;

import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

public class MsgPackServer {
    public static void main(String[] args) throws InterruptedException {
        NioEventLoopGroup group = new NioEventLoopGroup();
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        ChannelFuture future = serverBootstrap.group(group)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();
                        pipeline.addLast("msgDecode", new MsgDecodeHandler());
                        pipeline.addLast("printMsg", new MsgHandler());

                    }
                }).bind(9998).sync();

    }
}