Netty 入門示例


服務端代碼示例

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;


public class TimeServer {

    public void bind(int port) throws Exception {
        //配置服務端的NIO線程組
        //NioEventLoopGroup是個線程組,它包含了一組NIO線程,專門用於網絡事件的處理,
        //實際上它們就是Reactor線程組。
        //這里創建兩個的原因是一個用於服務端接受客戶端的連接,另一個用於進行SocketChannel的網絡讀寫。
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            //創建ServerBootstrap對象,它是Netty用於啟動NIO服務端的輔助啟動類,目的是降低服務端的開發復雜度。
            ServerBootstrap b = new ServerBootstrap();
            //調用ServerBootstrap的group方法,將兩個NIO線程組當作入參傳遞到ServerBootstrap中。
            //接着設置創建的Channel為NioServerSocketChannel,它的功能對應於JDK NIO類庫中的ServerSocketChannel類。
            //然后配置NioServerSocketChannel的TCP參數,此處將它的backlog設置為1024,
            //最后綁定I/O事件的處理類ChildChannelHandler,它的作用類似於Reactor模式中的handler類,
            //主要用於處理網絡I/O事件,例如記錄日志、對消息進行編解碼等。
            b.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 1024)
                    .childHandler(new ChildChannelHandler());
            //綁定端口,同步等待成功
            //服務端啟動輔助類配置完成之后,調用它的bind方法綁定監聽端口
            //隨后,調用它的同步阻塞方法sync等待綁定操作完成。
            //完成之后Netty會返回一個ChannelFuture,它的功能類似於JDK的java.util.concurrent.Future,主要用於異步操作的通知回調。
            ChannelFuture f = b.bind(port).sync();

            //等待服務端監聽端口關閉
            //使用f.channel().closeFuture().sync()方法進行阻塞,等待服務端鏈路關閉之后main函數才退出。
            f.channel().closeFuture().sync();
        } finally {
            //優雅退出,釋放線程池資源
            //調用NIO線程組的shutdownGracefully進行優雅退出,它會釋放跟shutdownGracefully相關聯的資源。
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    private class ChildChannelHandler extends ChannelInitializer {
        @Override
        protected void initChannel(Channel channel) throws Exception {
            channel.pipeline().addLast(new TimeServerHandler());
        }
    }

    public static void main(String[] args) throws Exception {
        new TimeServer().bind(8080);
    }
}

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

//TimeServerHandler繼承自ChannelHandlerAdapter,它用於對網絡事件進行讀寫操作
//通常我們只需要關注channelRead和exceptionCaught方法。
public class TimeServerHandler extends ChannelHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        //做類型轉換,將msg轉換成Netty的ByteBuf對象。
        //ByteBuf類似於JDK中的java.nio.ByteBuffer 對象,不過它提供了更加強大和靈活的功能。
        ByteBuf buf = (ByteBuf) msg;
        //通過ByteBuf的readableBytes方法可以獲取緩沖區可讀的字節數,
        //根據可讀的字節數創建byte數組
        byte[] req = new byte[buf.readableBytes()];
        //通過ByteBuf的readBytes方法將緩沖區中的字節數組復制到新建的byte數組中
        buf.readBytes(req);
        //通過new String構造函數獲取請求消息。
        String body = new String(req, "UTF-8");
        System.out.println("The time server receive order : " + body);
        //如果是"QUERY TIME ORDER"則創建應答消息,
        String currentTime = "QUERY TIME ORDER".equalsIgnoreCase(body) ? new java.util.Date(
                System.currentTimeMillis()).toString() : "BAD ORDER";
        ByteBuf resp = Unpooled.copiedBuffer(currentTime.getBytes());
        //通過ChannelHandlerContext的write方法異步發送應答消息給客戶端。
        ctx.write(resp);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        //調用了ChannelHandlerContext的flush方法,它的作用是將消息發送隊列中的消息寫入到SocketChannel中發送給對方。
        //從性能角度考慮,為了防止頻繁地喚醒Selector進行消息發送,
        //Netty的write方法並不直接將消息寫入SocketChannel中,調用write方法只是把待發送的消息放到發送緩沖數組中,
        //再通過調用flush方法,將發送緩沖區中的消息全部寫到SocketChannel中。
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        //當發生異常時,關閉ChannelHandlerContext,釋放和ChannelHandlerContext相關聯的句柄等資源。
        ctx.close();
    }
}

客戶端代碼示例:

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

public class TimeClient {

    public void connect(int port, String host) throws Exception {
        // 配置客戶端NIO線程組
        //首先創建客戶端處理I/O讀寫的NioEventLoop Group線程組
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            //繼續創建客戶端輔助啟動類Bootstrap,隨后需要對其進行配置。
            //與服務端不同的是,它的Channel需要設置為NioSocketChannel
            //然后為其添加handler,此處為了簡單直接創建匿名內部類,實現initChannel方法,
            //其作用是當創建NioSocketChannel成功之后,
            //在初始化它的時候將它的ChannelHandler設置到ChannelPipeline中,用於處理網絡I/O事件。
            Bootstrap b = new Bootstrap();
            b.group(group).channel(NioSocketChannel.class)
                    .option(ChannelOption.TCP_NODELAY, true)
                    .handler(new ChannelInitializer() {
                        @Override
                        protected void initChannel(Channel channel) throws Exception {
                            channel.pipeline().addLast(new TimeClientHandler());
                        }
                    });

            // 發起異步連接操作
            //客戶端啟動輔助類設置完成之后,調用connect方法發起異步連接,
            //然后調用同步方法等待連接成功。
            ChannelFuture f = b.connect(host, port).sync();

            // 等待客戶端鏈路關閉
            //當客戶端連接關閉之后,客戶端主函數退出.
            f.channel().closeFuture().sync();
        } finally {
            // 優雅退出,釋放NIO線程組
            //在退出之前,釋放NIO線程組的資源。
            group.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws Exception {
        new TimeClient().connect(8080, "127.0.0.1");
    }
}


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

//重點關注三個方法:channelActive、channelRead和exceptionCaught。
public class TimeClientHandler extends ChannelHandlerAdapter {

    private final ByteBuf firstMessage;

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

    //當客戶端和服務端TCP鏈路建立成功之后,Netty的NIO線程會調用channelActive方法
    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        //發送查詢時間的指令給服務端
        //調用ChannelHandlerContext的writeAndFlush方法將請求消息發送給服務端。
        ctx.writeAndFlush(firstMessage);
    }

    //當服務端返回應答消息時,channelRead方法被調用
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg)throws Exception {
        //從Netty的ByteBuf中讀取並打印應答消息。
        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) {
        // 釋放資源
        //當發生異常時,打印異常日志,釋放客戶端資源。
        ctx.close();
    }
}

pom.xml

        <dependency>
            <groupId>io.netty</groupId>
            <artifactId>netty-all</artifactId>
            <version>5.0.0.Alpha1</version>
        </dependency>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM