美文网首页
Netty的简单Demo

Netty的简单Demo

作者: 没意思先生1995 | 来源:发表于2017-04-16 16:41 被阅读0次

TimeServer:

public class TimeServer {
    public void bind(int port) throws Exception {
        // 配置服务端的NIO线程组
        //用于网络事件处理
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            //启动NIO服务端的辅助启动类
            ServerBootstrap b = new ServerBootstrap();
            //将创建的channel作为ServerSocketChannel
            b.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 1024)
                .childHandler(new ChildChannelHandler());
            // 绑定端口,同步等待成功
            ChannelFuture f = b.bind(port).sync();

            // 等待服务端监听端口关闭
            f.channel().closeFuture().sync();
        } finally {
            // 优雅退出,释放线程池资源
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
    
    private class ChildChannelHandler extends ChannelInitializer<SocketChannel>{

        @Override
        protected void initChannel(SocketChannel sc) throws Exception {
            sc.pipeline().addLast(new TimeServerHandler());
        }
    }
    
    public static void main(String[] args) throws Exception {
        int port=8080;
        if(args!=null&&args.length>0){
            try {
                port=Integer.valueOf(args[0]);
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
        }
        new TimeServer().bind(port);
    }
}

TimeServerHandler(channelHandlerAdapter部分方法只有5.0.0才有):

public class TimeServerHandler extends ChannelHandlerAdapter {
    public void channelRead(ChannelHandlerContext ctx, Object msg)
            throws Exception {
        ByteBuf buf = (ByteBuf) msg;
        byte[] req = new byte[buf.readableBytes()];
        buf.readBytes(req);
        String body = new String(req, "UTF-8");
        System.out.println("The time server receive order : " + body);
        String currentTime = "QUERY TIME ORDER".equalsIgnoreCase(body) ? new java.util.Date(
                System.currentTimeMillis()).toString() : "BAD ORDER";
        ByteBuf resp = Unpooled.copiedBuffer(currentTime.getBytes());
        ctx.write(resp);
    }

    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        //netty的消息不直接写入channel,它放在缓冲数组,调用flush()才写入
        ctx.flush();
    }

    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        ctx.close();
    }
}

TimeClient:

public class TimeClient {
    public void connect(int port, String host) throws Exception {
        // 配置客户端NIO线程组
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group).channel(NioSocketChannel.class)
                    .option(ChannelOption.TCP_NODELAY, true)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        //初始化时将handler设置到ChannelPipeline
                        public void initChannel(SocketChannel ch)
                                throws Exception {
                            ch.pipeline().addLast(new TimeClientHandler());
                        }
                    });

            // 发起异步连接操作
            ChannelFuture f = b.connect(host, port).sync();

            // 当代客户端链路关闭
            f.channel().closeFuture().sync();
        } finally {
            // 优雅退出,释放NIO线程组
            group.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws Exception {
        int port = 8080;
        if (args != null && args.length > 0) {
            try {
                port = Integer.valueOf(args[0]);
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
        }
        new TimeClient().connect(port, "127.0.0.1");
    }
}

TimeClientHandler:

public class TimeClientHandler extends ChannelHandlerAdapter {

    private static final Logger logger = Logger
            .getLogger(TimeClientHandler.class.getName());

    private final ByteBuf firstMessage;

    /**
     * Creates a client-side handler.
     */
    public TimeClientHandler() {
        byte[] req = "QUERY TIME ORDER".getBytes();
        firstMessage = Unpooled.buffer(req.length);
        firstMessage.writeBytes(req);
    }
    //客户端和服务端TCP链路建立成功后调用此方法
    public void channelActive(ChannelHandlerContext ctx) {
        //通过此方法将消息发送给服务端
        ctx.writeAndFlush(firstMessage);
    }
    //服务端返回应答消息调用此方法
    public void channelRead(ChannelHandlerContext ctx, Object msg)
            throws Exception {
        ByteBuf buf = (ByteBuf) msg;
        byte[] req = new byte[buf.readableBytes()];
        buf.readBytes(req);
        String body = new String(req, "UTF-8");
        System.out.println("Now is : " + body);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        // 释放资源
        logger.warning("Unexpected exception from downstream : "
                + cause.getMessage());
        ctx.close();
    }
}

相关文章

  • Netty简单demo

    什么是Netty 以上是摘自《Essential Netty In Action》这本书,本文的内容也是本人读了这...

  • Netty的简单Demo

    TimeServer: TimeServerHandler(channelHandlerAdapter部分方法只有...

  • netty通信的简单demo

    seata中使用netty完成了TM、RM与TC之间的通信,若不熟悉netty的语法,那么阅读seata的源码是比...

  • Netty学习(二)使用及执行流程(篇幅略长)

    Netty简单使用 1.本文先介绍一下 server 的 demo 2.(重点是这个)根据代码跟踪一下 Netty...

  • netty基础-NIO简单demo

    BIO:阻塞IO流,可以是文件流也可以是网络中请求流。 clientA请求Service服务器首先建立连接发送in...

  • Netty笔记4-如何实现长连接

    ​ 前面三章介绍了Netty的一些基本用法,这一章介绍怎么使用Netty来实现一个简单的长连接demo。 Ne...

  • 高性能NIO框架Netty-对象传输

    上篇文章高性能NIO框架Netty入门篇我们对Netty做了一个简单的介绍,并且写了一个入门的Demo,客户端往服...

  • Netty Demo

    导入netty相关包 实现ChannelInboundHandlerAdapter接口 3.启动服务器 启动客户端...

  • 一个简单的Netty Demo

    netty ChannelFuture ChannelFuture的作用是用来保存Channel异步操作的结果。...

  • netty分析(一) -- 服务启动流程

    如果还不了解原生nio的socket编程,可以看前置博文 一个简单的Demo程序 先贴一个简单的netty的exa...

网友评论

      本文标题:Netty的简单Demo

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