美文网首页
Netty学习--第一个netty程序

Netty学习--第一个netty程序

作者: 何何与呵呵呵 | 来源:发表于2019-01-04 08:41 被阅读0次
    1.服务端
    package com.hehe.netty.server;
    
    import io.netty.bootstrap.ServerBootstrap;
    import io.netty.channel.ChannelFuture;
    import io.netty.channel.ChannelInitializer;
    import io.netty.channel.EventLoopGroup;
    import io.netty.channel.nio.NioEventLoopGroup;
    import io.netty.channel.socket.SocketChannel;
    import io.netty.channel.socket.nio.NioServerSocketChannel;
    
    import java.net.InetSocketAddress;
    
    /**
     * @author helong
     * @date 2019/1/2 9:30
     * @description 引导服务器
     */
    
    public class EchoServer {
    
        private final int port;
        public EchoServer(int port) {
            this.port = port;
        }
        public static void main(String[] args) throws Exception {
            if (args.length != 1) {
                System.err.println("Usage: " + EchoServer.class.getSimpleName() +" <port>");
            }
    //        int port = Integer.parseInt(args[0]); // 设置端口值(如果端口参数的格式不正确,则抛出一个NumberFormatException)
            int port = 9999;
            new EchoServer(port).start();
        }
    
        public void start() throws Exception {
            final EchoServerHandler serverHandler = new EchoServerHandler();
            EventLoopGroup group = new NioEventLoopGroup(); // 创建Event-LoopGroup
            try {
                ServerBootstrap b = new ServerBootstrap(); //创建Server-Bootstrap
                b.group(group)
                        .channel(NioServerSocketChannel.class) // 指定所使用的NIO 传输Channel
                        .localAddress(new InetSocketAddress(port)) // 使用指定的端口设置套接字地址
                        .childHandler(new ChannelInitializer<SocketChannel>(){ // 添加一个EchoServer-Handler 到子Channel的ChannelPipeline
                            @Override
                            public void initChannel(SocketChannel ch)throws Exception {
                                ch.pipeline().addLast(serverHandler);
                            }
                        });
                ChannelFuture f = b.bind().sync(); // 异步地绑定服务器;调用sync()方法阻塞等待直到绑定完成
                f.channel().closeFuture().sync(); // 获取Channel 的CloseFuture,并且阻塞当前线程直到它完成
            } finally {
                group.shutdownGracefully().sync();// 关闭EventLoopGroup,释放所有的资源
            }
        }
    
    }
    
    2.服务端处理
    package com.hehe.netty.server;
    
    import io.netty.buffer.ByteBuf;
    import io.netty.buffer.Unpooled;
    import io.netty.channel.ChannelFutureListener;
    import io.netty.channel.ChannelHandler;
    import io.netty.channel.ChannelHandlerContext;
    import io.netty.channel.ChannelInboundHandlerAdapter;
    import io.netty.util.CharsetUtil;
    
    /**
     * @author helong
     * @date 2019/1/2 8:58
     * @description netty服务端
     */
    
    @ChannelHandler.Sharable // 标示一个Channel-Handler 可以被多个Channel 安全地共享
    public class EchoServerHandler extends ChannelInboundHandlerAdapter {
    
        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) {
            ByteBuf in = (ByteBuf) msg;
            System.out.println(
                    "Server received: " + in.toString(CharsetUtil.UTF_8));
            ctx.write(in); // 将接收到的消息写给发送者,而不冲刷出站消息
        }
    
        @Override
        public void channelReadComplete(ChannelHandlerContext ctx) {
            ctx.writeAndFlush(Unpooled.EMPTY_BUFFER)
                    .addListener(ChannelFutureListener.CLOSE); // 将未决消息冲刷到远程节点,并且关闭该Channel
        }
    
        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
            cause.printStackTrace();
            ctx.close();
        }
    
    }
    
    3.客户端的主类
    package com.hehe.netty.client;
    
    import io.netty.bootstrap.Bootstrap;
    import io.netty.channel.ChannelFuture;
    import io.netty.channel.ChannelInitializer;
    import io.netty.channel.EventLoopGroup;
    import io.netty.channel.nio.NioEventLoopGroup;
    import io.netty.channel.socket.SocketChannel;
    import io.netty.channel.socket.nio.NioSocketChannel;
    
    import java.net.InetSocketAddress;
    
    /**
     * @author helong
     * @date 2019/1/3 8:47
     * @description 客户端的主类
     */
    
    public class EchoClient {
        private final String host;
        private final int port;
        public EchoClient(String host, int port) {
            this.host = host;
            this.port = port;
        }
        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)) // 设置服务器的InetSocketAddress
                        .handler(new ChannelInitializer<SocketChannel>() {
                            @Override
                            public void initChannel(SocketChannel ch)throws Exception {
                                ch.pipeline().addLast(new EchoClientHandler());
                            }
                        });
                ChannelFuture f = b.connect().sync();// 连接到远程节点,阻塞等待直到连接完成
                f.channel().closeFuture().sync(); // 阻塞,直到Channel 关闭
            } finally {
                group.shutdownGracefully().sync(); // 关闭线程池并且释放所有的资源
            }
        }
        public static void main(String[] args) throws Exception {
    //        if (args.length != 2) {
    //            System.err.println("Usage: " + EchoClient.class.getSimpleName() +" <host> <port>");
    //            return;
    //        }
    //        String host = args[0];
            String host = "0:0:0:0:0:0:0:0";
    //        int port = Integer.parseInt(args[1]);
            int port = 9999;
            new EchoClient(host, port).start();
        }
    }
    
    4.客户端处理
    package com.hehe.netty.client;
    
    import io.netty.buffer.ByteBuf;
    import io.netty.buffer.Unpooled;
    import io.netty.channel.ChannelHandler;
    import io.netty.channel.ChannelHandlerContext;
    import io.netty.channel.SimpleChannelInboundHandler;
    import io.netty.util.CharsetUtil;
    
    /**
     * @author helong
     * @date 2019/1/3 8:35
     * @description netty客户端
     */
    
    @ChannelHandler.Sharable // 被所有channel共享
    public class EchoClientHandler extends SimpleChannelInboundHandler<ByteBuf> {
        /**
         * 当被通知Channel是活跃的时候,发送一条消息
         * @param ctx
         */
        @Override
        public void channelActive(ChannelHandlerContext ctx) {
            ctx.writeAndFlush(Unpooled.copiedBuffer("Netty rocks!", CharsetUtil.UTF_8));
            ctx.writeAndFlush(Unpooled.copiedBuffer("heiheihei!", CharsetUtil.UTF_8));
        }
    
        /**
         * 记录已接收消息的转储
         * @param ctx
         * @param in
         */
        @Override
        public void channelRead0(ChannelHandlerContext ctx, ByteBuf in) {
            System.out.println("Client received: " + in.toString(CharsetUtil.UTF_8));
        }
    
        /**
         * 异常记录
         * @param ctx
         * @param cause
         */
        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
            cause.printStackTrace();
            ctx.close();
        }
    }
    

    相关文章

      网友评论

          本文标题:Netty学习--第一个netty程序

          本文链接:https://www.haomeiwen.com/subject/pyocrqtx.html