Netty小demo(二)

实验

改造NIO实现的TimeClient

代码

import io.netty.bootstrap.Bootstrap;
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.NioSocketChannel;

import java.net.InetSocketAddress;

/**
 * Created by liqiushi on 2017/12/14.
 */
public class TimeClient {
    public static void main(String[] args) {
        EventLoopGroup workGroup = new NioEventLoopGroup();

        Bootstrap b = new Bootstrap();
        b.group(workGroup)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY,true)
                .handler(new ChannelInitializer() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new TimeClientHandler());
                    }
                });

        try {
            ChannelFuture connectFuture = b.connect(new InetSocketAddress("127.0.0.1",8001)).sync();
            connectFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            System.out.println("Relase group!");
            workGroup.shutdownGracefully();
        }
    }
}
  • TimeClientHandler
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

/**
 * Created by liqiushi on 2017/12/14.
 */
public class TimeClientHandler extends ChannelInboundHandlerAdapter {

    private ByteBuf firstSendMsg;

    public TimeClientHandler() {
        byte[] req = "QUERY TIME ORDER".getBytes();
        firstSendMsg = Unpooled.buffer(req.length);
        firstSendMsg.writeBytes(req);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("Send firstSendMsg!");
        ctx.writeAndFlush(firstSendMsg);
        super.channelActive(ctx);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("Client read!");
        ByteBuf recvBuf = (ByteBuf) msg;
        byte[] req = new byte[recvBuf.readableBytes()];
        recvBuf.readBytes(req);
        String out = new String(req, "UTF-8");
        System.out.println("Now is :" + out);
        super.channelRead(ctx, msg);
    }

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

你可能感兴趣的:(Netty小demo(二))