zoukankan      html  css  js  c++  java
  • netty入门代码学习

    服务端代码:

    package com.lsp.netty;
    
    /**
     * @author lishupeng
     * @create 2017-05-27 下午 3:48
     **/
    import io.netty.bootstrap.ServerBootstrap;
    import io.netty.buffer.ByteBuf;
    import io.netty.buffer.Unpooled;
    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;
    import io.netty.handler.codec.DelimiterBasedFrameDecoder;
    import io.netty.handler.codec.string.StringDecoder;
    
    
    public class Socket {
        public static void main(String[] args) throws InterruptedException {
            //1.第一个线程组是用于接收Client端连接的
            EventLoopGroup bossGroup = new NioEventLoopGroup();
            //2.第二个线程组是用于实际的业务处理的
            EventLoopGroup workerGroup = new NioEventLoopGroup();
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup);//绑定两个线程池
            b.channel(NioServerSocketChannel.class);//指定NIO的模式,如果是客户端就是NioSocketChannel
            b.option(ChannelOption.SO_BACKLOG, 1024);//TCP的缓冲区设置
            b.option(ChannelOption.SO_SNDBUF, 32*1024);//设置发送缓冲的大小
            b.option(ChannelOption.SO_RCVBUF, 32*1024);//设置接收缓冲区大小
            b.option(ChannelOption.SO_KEEPALIVE, true);//保持连续
            b.childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel sc) throws Exception {
                    ByteBuf buf = Unpooled.copiedBuffer("$_".getBytes());//拆包粘包定义结束字符串(第一种解决方案)
                    sc.pipeline().addLast(new DelimiterBasedFrameDecoder(1024,buf));//在管道中加入结束字符串
                    //  sc.pipeline().addLast(new FixedLengthFrameDecoder(200));第二种定长
                    sc.pipeline().addLast(new StringDecoder());//定义接收类型为字符串把ByteBuf转成String
                    sc.pipeline().addLast(new ServertHandler());//在这里配置具体数据接收方法的处理
                }
            });
            ChannelFuture future = b.bind(8765).sync();//绑定端口
            future.channel().closeFuture().sync();//等待关闭(程序阻塞在这里等待客户端请求)
            bossGroup.shutdownGracefully();//关闭线程
            workerGroup.shutdownGracefully();//关闭线程
        }
    }
    package com.lsp.netty;
    
    import io.netty.buffer.Unpooled;
    import io.netty.channel.ChannelHandlerAdapter;
    import io.netty.channel.ChannelHandlerContext;
    
    /**
     * @author lishupeng
     * @create 2017-05-27 下午 3:48
     **/
    public class ServertHandler extends ChannelHandlerAdapter {
    
        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            String body = (String) msg;
            System.out.println("server"+body);//前面已经定义了接收为字符串,这里直接接收字符串就可以
            //服务端给客户端的响应
            String response= " hi client!$_";//发送的数据以定义结束的字符串结尾
            ctx.writeAndFlush(Unpooled.copiedBuffer(response.getBytes()));//发送必须还是ByteBuf类型
        }
    
        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            cause.printStackTrace();
            ctx.close();
        }
    
    }

    客户端代码:

    package com.lsp.netty;
    
    import io.netty.bootstrap.Bootstrap;
    import io.netty.buffer.ByteBuf;
    import io.netty.buffer.Unpooled;
    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 io.netty.handler.codec.DelimiterBasedFrameDecoder;
    import io.netty.handler.codec.string.StringDecoder;
    
    /**
     * @author lishupeng
     * @create 2017-05-27 下午 3:48
     **/
    public class Client {
        public static void main(String[] args) throws InterruptedException {
            EventLoopGroup worker = new NioEventLoopGroup();
            Bootstrap b = new Bootstrap();
            b.group(worker)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel sc) throws Exception {
                            ByteBuf buf = Unpooled.copiedBuffer("$_".getBytes());
                            sc.pipeline().addLast(new DelimiterBasedFrameDecoder(1024,buf));
                            sc.pipeline().addLast(new StringDecoder());
                            sc.pipeline().addLast(new ClientHandler());
                        }
                    });
            ChannelFuture f=b.connect("127.0.0.1",8765).sync();
            f.channel().writeAndFlush(Unpooled.copiedBuffer(" hi server2$_".getBytes()));
            f.channel().writeAndFlush(Unpooled.copiedBuffer(" hi server3$_".getBytes()));
            f.channel().writeAndFlush(Unpooled.copiedBuffer(" hi server4$_".getBytes()));
            f.channel().closeFuture().sync();
            worker.shutdownGracefully();
        }
    
    }
    package com.lsp.netty;
    
    import io.netty.channel.ChannelHandlerAdapter;
    import io.netty.channel.ChannelHandlerContext;
    import io.netty.util.ReferenceCountUtil;
    
    /**
     * @author lishupeng
     * @create 2017-05-27 下午 3:49
     **/
    public class ClientHandler extends ChannelHandlerAdapter {
        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            try {
                System.out.println("client"+msg.toString());
            } finally {
                ReferenceCountUtil.release(msg);//释放缓冲区
            }
        }
    
        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            cause.printStackTrace();
            ctx.close();
        }
    }
  • 相关阅读:
    上传几张智能开关产品图片
    python+ueditor+七牛云存储整合
    Shell脚本检查memcache进程并自己主动重新启动
    Cocos2dx 3.x创建Layer的步骤
    HDU 5009 Paint Pearls (动态规划)
    (转)Spring4.2.5+Hibernate4.3.11+Struts2.3.24整合开发
    (转)Spring提供的CharacterEncoding和OpenSessionInView功能
    (转)为Spring集成的Hibernate配置二级缓存
    (转)Spring4.2.5+Hibernate4.3.11+Struts1.3.8集成方案二
    (转)Spring4.2.5+Hibernate4.3.11+Struts1.3.8集成方案一
  • 原文地址:https://www.cnblogs.com/lishupeng/p/6913416.html
Copyright © 2011-2022 走看看