美文网首页
netty网络编程-4.netty简易的Server与Clien

netty网络编程-4.netty简易的Server与Clien

作者: 笨鸡 | 来源:发表于2020-04-01 01:08 被阅读0次

    NettyServerHandler

    package com.ctgu.netty.basic;
    
    import io.netty.buffer.ByteBuf;
    import io.netty.buffer.Unpooled;
    import io.netty.channel.ChannelHandlerContext;
    import io.netty.channel.ChannelInboundHandlerAdapter;
    import io.netty.util.CharsetUtil;
    
    public class NettyServerHandler extends ChannelInboundHandlerAdapter {
        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            ctx.close();
        }
    
        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            System.out.println("Server:" + ctx);
            System.out.println("ServerMsg:" + msg);
            ByteBuf buf = (ByteBuf) msg;
            try {
                String str = BufDecoder.buf2string(buf);
                if (str.length() > 0) {
                    System.out.println("客户端发来的消息:" + str);
                    System.out.flush();
                } else {
                    System.out.println("不能读啊");
                }
            } finally {
                buf.release();
            }
        }
    
        @Override
        public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
            ctx.writeAndFlush(Unpooled.copiedBuffer("就是没钱", CharsetUtil.UTF_8));
        }
    }
    

    NettyServer

    package com.ctgu.netty.basic;
    
    import io.netty.bootstrap.ServerBootstrap;
    import io.netty.channel.ChannelFuture;
    import io.netty.channel.ChannelInitializer;
    import io.netty.channel.ChannelOption;
    import io.netty.channel.EventLoopGroup;
    import io.netty.channel.nio.NioEventLoopGroup;
    import io.netty.channel.socket.SocketChannel;
    import io.netty.channel.socket.nio.NioServerSocketChannel;
    
    public class NettyServer {
        public static void main(String[] args) throws InterruptedException {
            EventLoopGroup bossGroup = new NioEventLoopGroup();
            EventLoopGroup workerGroup = new NioEventLoopGroup();
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup);
            b.channel(NioServerSocketChannel.class);
            b.option(ChannelOption.SO_BACKLOG, 128);
            b.childOption(ChannelOption.SO_KEEPALIVE, true);
            b.childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel sc) throws Exception {
                    sc.pipeline().addLast(new NettyServerHandler());
                }
            });
            System.out.println("-------Server is ready--------");
            ChannelFuture cf = b.bind(9999).sync();
            System.out.println("-------Server is starting--------");
            cf.channel().closeFuture().sync();
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
    

    NettyClientHandler

    package com.ctgu.netty.basic;
    
    import io.netty.buffer.ByteBuf;
    import io.netty.buffer.Unpooled;
    import io.netty.channel.ChannelHandlerContext;
    import io.netty.channel.ChannelInboundHandlerAdapter;
    import io.netty.util.CharsetUtil;
    
    
    public class NettyClientHandler extends ChannelInboundHandlerAdapter {
        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception {
            System.out.println("Client:" + ctx);
            ctx.writeAndFlush(Unpooled.copiedBuffer("老板,快还钱", CharsetUtil.UTF_8));
        }
    
        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            ByteBuf buf = (ByteBuf) msg;
            System.out.println("服务端发来的消息:" + BufDecoder.buf2string(buf));
        }
    
    }
    

    NettyClient

    package com.ctgu.netty.basic;
    
    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;
    
    public class NettyClient {
        public static void main(String[] args) throws InterruptedException {
            EventLoopGroup group = new NioEventLoopGroup();
            Bootstrap b = new Bootstrap();
            b.group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel sc) throws Exception {
                            sc.pipeline().addLast(new NettyClientHandler());
                        }
                    });
            System.out.println("----------Client is ready--------");
            ChannelFuture cf = b.connect("127.0.0.1", 9999);
            System.out.println("----------Client is Starting--------");
            cf.channel().closeFuture().sync();
            group.shutdownGracefully();
        }
    }
    

    BufDecoder

    package com.ctgu.netty.basic;
    
    import io.netty.buffer.ByteBuf;
    
    public class BufDecoder {
        public static String buf2string(ByteBuf buf) {
            byte[] b = new byte[buf.readableBytes()];
            //把数据从bytebuf转移到byte[]
            buf.getBytes(0, b);
            //将byte[]转成字符串用于打印
            return new String(b);
        }
    }
    

    相关文章

      网友评论

          本文标题:netty网络编程-4.netty简易的Server与Clien

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