T
T
TheRevan2018-03-14 08:00:42
Java
TheRevan, 2018-03-14 08:00:42

How to pass an object through netty?

How to transfer an object over the network, implementation examples are of interest, preferably on version 4 and higher. Why do you need encoder and decoder if conversions to Pocket do not occur in them (in latest versions)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gornostaev, 2018-03-14
@TheRevan

Codecs, including encoders and decoders, are needed just to convert the data entering the channel and leaving it. You can do all this in one handler, but separating the logic and following the principles of the framework makes it easier to debug and maintain the code. I don't know what Pocket is, but the latest versions use the same codecs as the previous ones.

import java.io.Serializable;

public class Person implements Serializable {
    private final Long id;
    private String name;

    public Person(Long id, String name) {
        this.id = id;
        this.name = name;
    }

    public Long getId() {
        return id;
    }

    public String getName() {
        return name;
    }

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

public class SimpleClient {
    public static void main(String[] args) throws Exception {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            new Bootstrap().group(group)
                           .channel(NioSocketChannel.class)
                           .handler(new ChannelInitializer<SocketChannel>() {
                                @Override
                                public void initChannel(SocketChannel socketChannel) {
                                    ChannelPipeline pipeline = socketChannel.pipeline();
                                    pipeline.addLast(new ObjectEncoder());
                                    pipeline.addLast(new ObjectDecoder(ClassResolvers.cacheDisabled(null)));
                                    pipeline.addLast(new ChannelInboundHandlerAdapter() {
                                        @Override
                                        public void channelActive(ChannelHandlerContext ctx) throws Exception {
                                            ctx.writeAndFlush(new Person(1L, "John"));
                                        }

                                        @Override
                                        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                            Person person = (Person) msg;
                                            System.out.println(person);
                                        }
                                    });
                                }
                            })
                            .connect("localhost", 8080)
                            .sync()
                            .channel()
                            .closeFuture()
                            .sync();

        } finally {
            group.shutdownGracefully();
        }
    }
}

public class SimpleServer {
    public static void main(String[] args) throws Exception {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            new ServerBootstrap().group(group)
                                 .channel(NioServerSocketChannel.class)
                                 .childHandler(new ChannelInitializer<SocketChannel>() {
                                    @Override
                                    public void initChannel(SocketChannel socketChannel) {
                                        ChannelPipeline pipeline = socketChannel.pipeline();
                                        pipeline.addLast(new ObjectEncoder());
                                        pipeline.addLast(new ObjectDecoder(ClassResolvers.cacheDisabled(null)));
                                        pipeline.addLast(new ChannelInboundHandlerAdapter() {
                                            @Override
                                            public void channelRead(ChannelHandlerContext ctx, Object msg) {
                                                Person person = (Person) msg;
                                                System.out.println(person);

                                                person.setName("John Doe");
                                                ctx.writeAndFlush(person)
                                                   .addListener(ChannelFutureListener.CLOSE);
                                            }

                                            @Override
                                            public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
                                                cause.printStackTrace();
                                                ctx.channel().close();
                                            }
                                        });
                                    }
                                 })
                                 .bind("localhost", 8080)
                                 .sync()
                                 .channel()
                                 .closeFuture()
                                 .syncUninterruptibly();

        } finally {
            group.shutdownGracefully();
        }
    }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question