netty入门demo

  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 MyClient extends ChannelInboundHandlerAdapter {
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("client recive msg"+msg);
        ctx.channel().writeAndFlush("client accpet mssage"+msg);
        ctx.close();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.print(" client exception is"+cause.getMessage());
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值