欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

netty入门demo

程序员文章站 2022-03-02 15:28:24
...

  netty原理链接

     https://www.oschina.net/question/16_9863

本文主要是手写一个demo入门:

  服务器:

public class MyNettyServer {

     private static  String IP="127.0.0.1";
     private static int port=1234;
     public void  run(){
         EventLoopGroup bossgroup =new NioEventLoopGroup();
         EventLoopGroup workgroup =new NioEventLoopGroup();

         ServerBootstrap serverBootstrap=new ServerBootstrap();
         try {
          serverBootstrap.group(bossgroup, workgroup)
                 .channel(NioServerSocketChannel.class)
                 .childHandler(new ChannelInitializer<Channel>() {
                     @Override
                     protected void initChannel(Channel channel) throws Exception {
                        ChannelPipeline pipeline=channel.pipeline();
                         pipeline.addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE,0,4,0,4));
                         pipeline.addLast(new StringDecoder(CharsetUtil.UTF_8));
                         pipeline.addLast(new StringEncoder(CharsetUtil.UTF_8));
                         pipeline.addLast(new MyHandler());
                     }
                 }).option(ChannelOption.SO_BACKLOG, 128)
                 .childOption(ChannelOption.SO_KEEPALIVE, true);
         ChannelFuture f = null;

             f = serverBootstrap.bind(port).sync();
             f.channel().closeFuture().sync();
         } catch (InterruptedException e) {
             e.printStackTrace();
         }finally {
             bossgroup.shutdownGracefully();
             workgroup.shutdownGracefully();
         }
     }

Haddler代码:

public class MyHandler  extends ChannelInboundHandlerAdapter {

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
      //  super.channelActive(ctx);
        System.out.println("---channelActive---");

    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
       // super.channelRead(ctx, msg);
        System.out.println("-----channelRead---"+msg);
        ctx.channel().writeAndFlush("server accpet mssage"+msg);
        ctx.close();
    }


    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
       // super.exceptionCaught(ctx, cause);
        System.out.println(" service exception is"+cause.getMessage());
    }
}

客户端代码:

public class NeetyClient implements Runnable {
    @Override
    public void run() {
        EventLoopGroup eventLoopGroup=new NioEventLoopGroup();

        Bootstrap bootstrap=new Bootstrap();
        try {
        bootstrap.group(eventLoopGroup);
        bootstrap.channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY,true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline pipeline=ch.pipeline();
                        pipeline.addLast("frameDecoder",new LengthFieldPrepender(4));
                        pipeline.addLast("decoder",new StringDecoder(CharsetUtil.UTF_8));
                        pipeline.addLast("encoder",new StringEncoder(CharsetUtil.UTF_8));
                        pipeline.addLast("handler",new MyClient());
                    }
                });
        for (int i=0;i<100;i++){



                ChannelFuture cf= bootstrap.connect("127.0.0.1",1234).sync();
                cf.channel().writeAndFlush("curr thread"+Thread.currentThread().getName());
                cf.channel().closeFuture().sync();
        }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {

        }
    }

客户端Handler:

public class MyHandler  extends ChannelInboundHandlerAdapter {

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
      //  super.channelActive(ctx);
        System.out.println("---channelActive---");

    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
       // super.channelRead(ctx, msg);
        System.out.println("-----channelRead---"+msg);
        ctx.channel().writeAndFlush("server accpet mssage"+msg);
        ctx.close();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
       // super.exceptionCaught(ctx, cause);
        System.out.println(" service exception is"+cause.getMessage());
    }
}
相关标签: netty