Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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();
- }
- }
- }
Add Comment
Please, Sign In to add comment