深入學習netty系列(1)

來源:互聯網
上載者:User

標籤:

 

一、Server端的編程模型

  • 範例程式碼1
EventLoopGroup bossGroup = new NioEventLoopGroup(1);EventLoopGroup workerGroup = new NioEventLoopGroup();try {     ServerBootstrap b = new ServerBootstrap();     b.group(bossGroup, workerGroup)      .channel(NioServerSocketChannel.class)      .handler(new LoggingHandler(LogLevel.INFO))      .childHandler(new ChannelInitializer<SocketChannel>(){          @Override           public void initChannel(SocketChannel ch) throws Exception {               ChannelPipeline p = ch.pipeline();
               p.addLast(new TimeServerHandler());           }      });      b.bind(PORT).sync().channel().closeFuture().sync();} finally {      bossGroup.shutdownGracefully();      workerGroup.shutdownGracefully();
}

由ServerBootstrap作為入口,用鏈式編程方式,分別調用group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG, 100).handler().

childHander()方法相當重要的方法,開發人員入手的地方,採用面向介面的方式,讓開發人實現ChannelInitializer介面,實現initChannel(SocketChannel ch)方法,把自己的Handler通過channelPipeline().addLast(new TimeServerHandler())來實現事件處理。

  • 範例程式碼2
@Sharablepublic class TimeServerHandler extends ChannelInboundHandlerAdapter {    @Override    public void channelActive(final ChannelHandlerContext ctx) {     final ByteBuf time = ctx.alloc().buffer(4); // (2)         time.writeInt((int) (System.currentTimeMillis() / 1000L + 2208988800L));         final ChannelFuture f = ctx.writeAndFlush(time); // (3)         f.addListener(new ChannelFutureListener() {             @Override             public void operationComplete(ChannelFuture future) {                 assert f == future;                 ctx.close();             }         }); // (4)    }    @Override    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {        cause.printStackTrace();        ctx.close();    }}

二、client編程模型

  • 程式碼範例3
public class TimeClient {public static void main(String[] args) throws Exception {            new TimeClient().bind();        }private void bind() throws InterruptedException{        String host = "localhost";        int port = Integer.parseInt("8080");        EventLoopGroup workerGroup = new NioEventLoopGroup();        try {            Bootstrap b = new Bootstrap(); // (1)            b.group(workerGroup); // (2)            b.channel(NioSocketChannel.class); // (3)            b.option(ChannelOption.SO_KEEPALIVE, true); // (4)            b.handler(new channelHandler());            // 啟動用戶端            ChannelFuture f = b.connect(host, port).sync(); // (5)            // 等待串連關閉            f.channel().closeFuture().sync();        } finally {            workerGroup.shutdownGracefully();        }}private class channelHandler extends ChannelInitializer<SocketChannel>{@Overrideprotected void initChannel(SocketChannel ch) throws Exception {ch.pipeline().addLast(new TimeClientHandler());}}}
 
public class TimeClientHandler extends ChannelInboundHandlerAdapter {    private static final SimpleDateFormat sdf = new SimpleDateFormat("yy-MM-dd HH:mm:ss");    @Override    public void channelRead(ChannelHandlerContext ctx, Object msg) {        ByteBuf m = (ByteBuf) msg; // (1)        try {            long currentTimeMillis = (m.readUnsignedInt() - 2208988800L) * 1000L;            System.out.println(sdf.format(new Date(currentTimeMillis)));            ctx.close();        } finally {            m.release();        }    }    @Override    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {        cause.printStackTrace();        ctx.close();    }}

深入學習netty系列(1)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.