Netty(一)——Netty入门程序
轉載請注明出處:http://www.cnblogs.com/Joanna-Yan/p/7447618.html
有興趣的可先了解下:4種I/O的對比與選型
主要內容包括:
- Netty開發環境的搭建
- 服務端程序TimeServer開發
- 客戶端程序TimeClient開發
- 時間服務器的運行和調試
1.Netty開發環境的搭建
前提:電腦上已經安裝了JDK1.7并配置了JDK的環境變量path。
從Netty官網下載Netty最新安裝包,解壓。
這時會發現里面包含了各個模塊的.jar包和源碼,由于我們直接以二進制類庫的方式使用Netty,所以只需要netty-all-4.1.15.Final.jar即可。
新建Java工程,引入netty-all-4.1.15.Final.jar。
2.Netty服務端開發
在使用Netty開發TimeServer之前,先回顧一下使用NIO進行服務端開發的步驟。
一個簡單的NIO服務端程序,如果需要我們直接使用JDK的NIO類庫進行開發,竟然需要經過繁瑣的十多步操作才能完成最基本的消息讀取和發送,這也是我們選擇Netty等NIO框架的原因了,下面我們看看使用Netty是如何輕松搞定服務端開發的。
package joanna.yan.netty;import io.netty.bootstrap.ServerBootstrap; 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.NioServerSocketChannel;public class TimeServer {public static void main(String[] args) throws Exception {int port=9090;if(args!=null&&args.length>0){try {port=Integer.valueOf(args[0]);} catch (Exception e) {// 采用默認值 }}new TimeServer().bind(port);}public void bind(int port) throws Exception{/** 配置服務端的NIO線程組,它包含了一組NIO線程,專門用于網絡事件的處理,實際上它們就是Reactor線程組。* 這里創建兩個的原因:一個用于服務端接受客戶端的連接,* 另一個用于進行SocketChannel的網絡讀寫。*/EventLoopGroup bossGroup=new NioEventLoopGroup();EventLoopGroup workerGroup=new NioEventLoopGroup();try {//ServerBootstrap對象,Netty用于啟動NIO服務端的輔助啟動類,目的是降低服務端的開發復雜度。ServerBootstrap b=new ServerBootstrap();b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG, 1024)/** 綁定I/O事件的處理類ChildChannelHandler,它的作用類似于Reactor模式中的handler類,* 主要用于處理網絡I/O事件,例如:記錄日志、對消息進行編解碼等。*/.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{//優雅退出,釋放線程池資源 bossGroup.shutdownGracefully();workerGroup.shutdownGracefully();}}private class ChildChannelHandler extends ChannelInitializer<SocketChannel>{@Overrideprotected void initChannel(SocketChannel arg0) throws Exception {arg0.pipeline().addLast(new TimeServerHandler()); } } } package joanna.yan.netty;import java.sql.Date; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter;/*** 用于對網絡事件進行讀寫操作* @author Joanna.Yan* @date 2017年11月8日下午4:15:13*/ //public class TimeServerHandler extends ChannelHandlerAdapter{//已摒棄 public class TimeServerHandler extends ChannelInboundHandlerAdapter{@Overridepublic void channelRead(ChannelHandlerContext ctx, Object msg)throws Exception {//ByteBuf類似于JDK中的java.nio.ByteBuffer對象,不過它提供了更加強大和靈活的功能。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 Date(System.currentTimeMillis()).toString() : "BAD ORDER";ByteBuf resp=Unpooled.copiedBuffer(currentTime.getBytes());ctx.write(resp);}@Overridepublic void channelReadComplete(ChannelHandlerContext ctx) throws Exception {/** ctx.flush();將消息發送隊列中的消息寫入到SocketChannel中發送給對方。* 從性能角度考慮,為了防止頻繁地喚醒Selector進行消息發送,Netty的write方法并不直接將消息寫入SocketChannel中,* 調用write方法只是把待發送的消息放到發送緩沖數組中,再通過調用flush方法,將發送緩沖區中的消息全部寫到SocketChannel中。*/ctx.flush();}@Overridepublic void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)throws Exception {ctx.close();} }3.Netty客戶端開發
package joanna.yan.netty;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;public class TimeClient {public static void main(String[] args) throws Exception {int port=9019;if(args!=null&&args.length>0){try {port=Integer.valueOf(args[0]);} catch (Exception e) {// 采用默認值 }}new TimeClient().connect(port, "127.0.0.1");}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>() {@Overrideprotected 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();}} } package joanna.yan.netty;import java.util.logging.Logger; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.channel.SimpleChannelInboundHandler;//public class TimeClientHandler extends ChannelHandlerAdapter{//已摒棄 public class TimeClientHandler extends ChannelInboundHandlerAdapter{private static final Logger logger=Logger.getLogger(TimeClientHandler.class.getName());private final ByteBuf firstMessage;public TimeClientHandler(){byte[] req="QUERY TIME ORDER".getBytes();firstMessage=Unpooled.buffer(req.length);firstMessage.writeBytes(req);}/*** 當客戶端和服務端TCP鏈路建立成功之后,Netty的NIO線程會調用channelActive方法,* 發送查詢時間的指令給服務端。*/@Overridepublic void channelActive(ChannelHandlerContext ctx) throws Exception {//將請求信息發送給服務端 ctx.writeAndFlush(firstMessage);}/*** 當服務端返回應答消息時調用channelRead方法*/@Overridepublic 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);}/*** 發生異常是,打印異常日志,釋放客戶端資源。*/@Overridepublic void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)throws Exception {//釋放資源logger.warning("Unexpected exception from downstream : "+cause.getMessage());ctx.close();} }?ChannelInboundHandlerAdapter和SimpleChannelInboundHandler的使用區分:
? ChannelInboundHandlerAdapter是普通類,而SimpleChannelInboundHandler<T>是抽象類,繼承SimpleChannelInboundHandler的類必須實現channelRead0方法;SimpleChannelInboundHandler<T>有一個重要特性,就是消息被讀取后,會自動釋放資源,常見的IM聊天軟件的機制就類似這種。而且SimpleChannelInboundHandler類是繼承了ChannelInboundHandlerAdapter類,重寫了channelRead()方法,并新增抽象類。絕大部分場景都可以用ChannelInboundHandlerAdapter來處理。
4.運行與調試
服務端運行結果:
客戶端運行結果:
?
運行結果正確。可以發現,通過Netty開發的NIO服務端和客戶端非常簡單,短短幾十行代碼就能完成之前NIO程序需要幾百行才能完成的功能。基于Netty的應用開發不但API使用簡單、開發模式固定,而且擴展性和定制性非常好,后面,會通過更多應用來介紹Netty的強大功能。
需要指出的是,本示例沒有考慮讀半包的處理,對于功能演示或者測試,上述程序沒有問題,但是稍加改造進行性能或者壓力測試,它就不能正確地工作了。后面我們會給出能夠正確處理半包消息的應用實例。
Netty(二)——TCP粘包/拆包
?如果此文對您有幫助,微信打賞我一下吧~
總結
以上是生活随笔為你收集整理的Netty(一)——Netty入门程序的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 原创:软银巨亏千亿?孙正义的投资帝国到底
- 下一篇: 揭秘各国总统们钟爱的手机