zoukankan      html  css  js  c++  java
  • 02_Netty实现的Echo服务器和客户端

    【Echo服务端】

    【EchoServer】

    public class EchoServer {
        private final int port;
    
        public EchoServer(int port) {
            this.port = port;
        }
    
        public static void main(String[] args) throws Exception {
            new EchoServer(9999).start();
        }
    
        public void start() throws Exception {
            NioEventLoopGroup group = new NioEventLoopGroup();
            try {
                ServerBootstrap b = new ServerBootstrap();   //创建ServerBootstrap
                b.group(group)
                        .channel(NioServerSocketChannel.class)   //指定NIO的传输Channel
                        .localAddress(new InetSocketAddress(port))
                        .childHandler(new ChannelInitializer<SocketChannel>() {
                            @Override
                            protected void initChannel(SocketChannel channel) throws Exception {
                                channel.pipeline().addLast(new EchoServerHandler());  //添加EchoServerHandler到Channel的ChannelPipeline
                            }
                        });
                ChannelFuture future = b.bind().sync();  //绑定服务器,sync等待服务器关闭
                System.out.println(EchoServer.class.getName() + " started and listen on " + future.channel().localAddress());
                future.channel().closeFuture().sync();
            } finally {
                group.shutdownGracefully().sync();
            }
        }
    
    }

    【EchoServerHandler】

    public class EchoServerHandler extends ChannelInboundHandlerAdapter {
    
        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            ByteBuf  in = (ByteBuf)msg;
            System.out.println("Server received:"+in.toString(CharsetUtil.UTF_8));
            ctx.write(in);
        }
    
        @Override
        public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
            ctx.writeAndFlush(Unpooled.EMPTY_BUFFER)
                    .addListener(ChannelFutureListener.CLOSE);
        }
    
        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            cause.printStackTrace();
            ctx.close();
        }
    
        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception {
            System.out.println("Server is Active......");
        }
    
    
    }

    [ 说明 ] 

    Echo的Handler实现了服务器的业务,决定了连接创建以后和收到信息后该如何处理。

    ChannelInboundHandler的实现方法作用
    channelRead()         //每次收到信息都会回调
    channelReadComplete() //channelRead执行结束时回调
    exceptionCaught()     //执行异常情况下会被回调。

    【Echo客户端】

    【EchoClient】

    public class EchoClient {
    
        private final String host;
        private final int port;
    
        public EchoClient(String host, int port) {
            this.host = host;
            this.port = port;
        }
    
        public static void main(String[] args) throws Exception{
            new EchoClient("127.0.0.1",9999).start();
        }
    
        public void start() throws Exception{
            EventLoopGroup group = new NioEventLoopGroup();
            try{
                Bootstrap b = new Bootstrap();
                b.group(group)
                        .channel(NioSocketChannel.class)
                        .remoteAddress(new InetSocketAddress(host,port))
                        .handler(new ChannelInitializer<SocketChannel>() {
                            @Override
                            protected void initChannel(SocketChannel channel) throws Exception {
                                channel.pipeline().addLast(
                                        new EchoClientHandler()
                                );
                            }
                        });
                ChannelFuture future = b.connect().sync();
                future.channel().closeFuture().sync();
            }finally {
                group.shutdownGracefully();
            }
        }
    }

    【EchoClientHandler】

    public class EchoClientHandler extends SimpleChannelInboundHandler<ByteBuf> {
    
        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception {
            System.out.println("client is active......");
            ctx.writeAndFlush(Unpooled.copiedBuffer("Netty rocks!", CharsetUtil.UTF_8));
        }
    
        @Override
        protected void channelRead0(ChannelHandlerContext channelHandlerContext, ByteBuf in) throws Exception {
            System.out.println("client received:"+ in.toString(CharsetUtil.UTF_8));
        }
    
        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            cause.printStackTrace();
            ctx.close();
        }
    
    }

    【运行结果】

    [ 服务端 ]

    [ 客户端 ]

  • 相关阅读:
    分子动力学中步长的选取
    提高编程能力刷题网站
    【18】如何把数据存储到MongoDB数据库
    【17】有关python面向对象编程的提高【多继承、多态、类属性、动态添加与限制添加属性与方法、@property】
    【16】有关python面向对象编程
    【15】杂记章节
    【14】文件读取并格式化处理
    【13】python time时间模块知识点备查
    【11】python 递归,深度优先搜索与广度优先搜索算法模拟实现
    6380. 【NOIP2019模拟2019.10.06】小w与最长路(path)
  • 原文地址:https://www.cnblogs.com/HigginCui/p/10324585.html
Copyright © 2011-2022 走看看