Netty权威指南_札记03_Netty入门应用

版权声明:士,不可以不弘毅,任重而道远 https://blog.csdn.net/superbeyone/article/details/83865390


Netty权威指南_札记03_Netty入门应用

0. 引入pom依赖

<!-- https://mvnrepository.com/artifact/io.netty/netty-all -->
<dependency>
   <groupId>io.netty</groupId>
    <artifactId>netty-all</artifactId>
    <version>5.0.0.Alpha1</version>
</dependency>

1. Netty服务端开发

1.1 Netty时间服务器服务端 TimeServer

import com.superbeyone.netty.handler.ChildChannelHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * @program: study_netty
 * @description: Netty时间服务器 服务端
 * @author: Mr.superbeyone
 * @create: 2018-11-09 09:52
 **/
public class TimeServer {

    public void bind(int port) {

        //配置服务端的NIO线程组
        NioEventLoopGroup boss = new NioEventLoopGroup();
        NioEventLoopGroup work = new NioEventLoopGroup();

        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(boss, work)
                   .channel(NioServerSocketChannel.class)
                   .option(ChannelOption.SO_BACKLOG, 1024)
                   .childHandler(new ChannelInitializer<SocketChannel>() {
                       @Override
                       protected void initChannel(SocketChannel socketChannel) throws Exception {
                           socketChannel.pipeline().addLast(new TimeServerHandler());	//添加handler
                       }
                   });

            //绑定端口,同步等待成功
            ChannelFuture future = bootstrap.bind(port).sync();

            //等待服务端监听端口关闭
            future.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //优雅退出,释放线程池资源
            boss.shutdownGracefully();
            work.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();
                System.out.println("服务端异常:"+e.getMessage());
            }

        }

        new TimeServer().bind(port);
    }
}

1.2 Netty时间服务器服务端 TimeServerHandler

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

import java.util.Date;

/**
 * @program: study_netty
 * @description: Netty时间服务器服务端
 * @author: Mr.superbeyone
 * @create: 2018-11-09 10:27
 **/
public class TimeServerHandler extends ChannelHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf byteBuf = (ByteBuf) msg;
        byte[] bytes = new byte[byteBuf.readableBytes()];
        byteBuf.readBytes(bytes);
        String body = new String(bytes, "UTF-8");
        System.out.println("The time server receive order:\t" + body);

        String currentTime = "query time order".equalsIgnoreCase(body) ? new Date().toString() : "Bad Order";

        ByteBuf resp = Unpooled.copiedBuffer(currentTime.getBytes());
        ctx.write(resp);

    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
        cause.printStackTrace();
    }
}

2. Netty客户端开发

2.1 Netty时间服务器客户端 TimeClient

import com.superbeyone.netty.handler.TimeClientHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

/**
 * @program: study_netty
 * @description: Netty时间服务器客户端NettyClient
 * @author: Mr.superbeyone
 * @create: 2018-11-09 10:37
 **/
public class TimeClient {

    public void connect(int port, String host) throws Exception {
        //配置客户端NIO线程组
        NioEventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group).channel(NioSocketChannel.class)
                    .option(ChannelOption.TCP_NODELAY, true)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline().addLast(new TimeClientHandler()); //添加handler
                        }
                    });
            //发起异步连接操作
            ChannelFuture future = bootstrap.connect(host, port).sync();

            //等待客户端链路关闭
            future.channel().closeFuture().sync();

        } catch (Exception e) {
            e.printStackTrace();
        } 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");
    }
}

2.2 Netty时间服务器客户端 TimeClientHandler

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

/**
 * @program: study_netty
 * @description: Netty时间服务器客户端 TimeClientHandler
 * @author: Mr.superbeyone
 * @create: 2018-11-09 11:20
 **/
public class TimeClientHandler extends ChannelHandlerAdapter {

    private final ByteBuf message;

    public TimeClientHandler() {
        byte[] bytes = "query time order".getBytes();
        message = Unpooled.buffer(bytes.length);
        message.writeBytes(bytes);
    }


    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        ctx.writeAndFlush(message);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf byteBuf = (ByteBuf) msg;
        byte[] bytes = new byte[byteBuf.readableBytes()];
        byteBuf.readBytes(bytes);
        String body = new String(bytes, "UTF-8");
        System.out.println("现在时间是:" + body);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("异常:" + cause.getMessage());
        //释放资源
        ctx.close();
    }
}

3. 执行结果

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/superbeyone/article/details/83865390