Netty4詳解二:開發第一個Netty應用程序
既然是入門,那我們就在這裏寫一個簡單的Demo,客戶端發送一個字符串到服務器端,服務器端接收字符串後再發送回客戶端。
2.1、配置開發環境
1.安裝JDK
2.去官網下載jar包
(或者通過pom構建)
2.2、認識下Netty的Client和Server
一個Netty應用模型,如下圖所示,但需要明白一點的是,我們寫的Server會自動處理多客戶端請求,理論上講,處理並發的能力決定於我們的係統配置及JDK的極限。

- Client連接到Server端
- 建立鏈接發送/接收數據
- Server端處理所有Client請求
這裏有一個形象的比喻來形容Netty客戶端和服務器端的交互模式,比如把你比作一個Client,把山比作一個Server,你走到山旁,就是和山建立了鏈接,你向山大喊了一聲,就代表向山發送了數據,你的喊聲經過山的反射形成了回聲,這個回聲就是服務器的響應數據。如果你離開,就代表斷開了鏈接,當然你也可以再回來。好多人可以同時向山大喊,他們的喊聲也一定會得到山的回應。
2.3 寫一個Netty Server
一個NettyServer程序主要由兩部分組成:
- BootsTrapping:配置服務器端基本信息
- ServerHandler:真正的業務邏輯處理
2.3.1 BootsTrapping的過程:
package NettyDemo.echo.server; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelInitializer; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioServerSocketChannel; import java.net.InetSocketAddress; import NettyDemo.echo.handler.EchoServerHandler; public class EchoServer { private static final int port = 8080; public void start() throws InterruptedException { ServerBootstrap b = new ServerBootstrap();// 引導輔助程序 EventLoopGroup group = new NioEventLoopGroup();// 通過nio方式來接收連接和處理連接 try { b.group(group); b.channel(NioServerSocketChannel.class);// 設置nio類型的channel b.localAddress(new InetSocketAddress(port));// 設置監聽端口 b.childHandler(new ChannelInitializer<SocketChannel>() {//有連接到達時會創建一個channel protected void initChannel(SocketChannel ch) throws Exception { // pipeline管理channel中的Handler,在channel隊列中添加一個handler來處理業務 ch.pipeline().addLast("myHandler", new EchoServerHandler()); } }); ChannelFuture f = b.bind().sync();// 配置完成,開始綁定server,通過調用sync同步方法阻塞直到綁定成功 System.out.println(EchoServer.class.getName() + " started and listen on " + f.channel().localAddress()); f.channel().closeFuture().sync();// 應用程序會一直等待,直到channel關閉 } catch (Exception e) { e.printStackTrace(); } finally { group.shutdownGracefully().sync();//關閉EventLoopGroup,釋放掉所有資源包括創建的線程 } } public static void main(String[] args) { try { new EchoServer().start(); } catch (InterruptedException e) { e.printStackTrace(); } } }
1. 創建一個ServerBootstrap實例
2. 創建一個EventLoopGroup來處理各種事件,如處理鏈接請求,發送接收數據等。
3. 定義本地InetSocketAddress( port)好讓Server綁定
4. 創建childHandler來處理每一個鏈接請求
5. 所有準備好之後調用ServerBootstrap.bind()方法綁定Server
2. 創建一個EventLoopGroup來處理各種事件,如處理鏈接請求,發送接收數據等。
3. 定義本地InetSocketAddress( port)好讓Server綁定
4. 創建childHandler來處理每一個鏈接請求
5. 所有準備好之後調用ServerBootstrap.bind()方法綁定Server
2.3.2 業務邏輯ServerHandler:
要想處理接收到的數據,我們必須繼承ChannelInboundHandlerAdapter接口,重寫裏麵的MessageReceive方法,每當有數據到達,此方法就會被調用(一般是Byte類型數組),我們就在這裏寫我們的業務邏輯:
package NettyDemo.echo.handler; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.channel.ChannelHandler.Sharable; /** * Sharable表示此對象在channel間共享 * handler類是我們的具體業務類 * */ @Sharable//注解@Sharable可以讓它在channels間共享 public class EchoServerHandler extends ChannelInboundHandlerAdapter{ public void channelRead(ChannelHandlerContext ctx, Object msg) { System.out.println("server received data :" + msg); ctx.write(msg);//寫回數據, } public void channelReadComplete(ChannelHandlerContext ctx) { ctx.writeAndFlush(Unpooled.EMPTY_BUFFER) //flush掉所有寫回的數據 .addListener(ChannelFutureListener.CLOSE); //當flush完成後關閉channel } public void exceptionCaught(ChannelHandlerContext ctx,Throwable cause) { cause.printStackTrace();//捕捉異常信息 ctx.close();//出現異常時關閉channel } }
2.3.3關於異常處理:
我們在上麵程序中也重寫了exceptionCaught方法,這裏就是對當異常出現時的處理。
2.4 寫一個Netty Client
一般一個簡單的Client會扮演如下角色:
- 連接到Server
- 向Server寫數據
- 等待Server返回數據
- 關閉連接
4.4.1 BootsTrapping的過程:
和Server端類似,隻不過Client端要同時指定連接主機的IP和Port。
package NettyDemo.echo.client; import io.netty.bootstrap.Bootstrap; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelInitializer; 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; import NettyDemo.echo.handler.EchoClientHandler; public class EchoClient { private final String host; private final int port; public EchoClient(String host, int port) { this.host = host; this.port = port; } public void start() throws Exception { EventLoopGroup group = new NioEventLoopGroup(); try { Bootstrap b = new Bootstrap(); b.group(group); b.channel(NioSocketChannel.class); b.remoteAddress(new InetSocketAddress(host, port)); b.handler(new ChannelInitializer<SocketChannel>() { public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new EchoClientHandler()); } }); ChannelFuture f = b.connect().sync(); f.addListener(new ChannelFutureListener() { public void operationComplete(ChannelFuture future) throws Exception { if(future.isSuccess()){ System.out.println("client connected"); }else{ System.out.println("server attemp failed"); future.cause().printStackTrace(); } } }); f.channel().closeFuture().sync(); } finally { group.shutdownGracefully().sync(); } } public static void main(String[] args) throws Exception { new EchoClient("127.0.0.1", 3331).start(); } }1. 創建一個ServerBootstrap實例
2. 創建一個EventLoopGroup來處理各種事件,如處理鏈接請求,發送接收數據等。
3. 定義一個遠程InetSocketAddress好讓客戶端連接
4. 當連接完成之後,Handler會被執行一次
5. 所有準備好之後調用ServerBootstrap.connect()方法連接Server
4.4.2 業務邏輯ClientHandler:
我們同樣繼承一個SimpleChannelInboundHandler來實現我們的Client,我們需要重寫其中的三個方法:
package NettyDemo.echo.handler; import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufUtil; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import io.netty.channel.ChannelHandler.Sharable; import io.netty.util.CharsetUtil; @Sharable public class EchoClientHandler extends SimpleChannelInboundHandler<ByteBuf> { /** *此方法會在連接到服務器後被調用 * */ public void channelActive(ChannelHandlerContext ctx) { ctx.write(Unpooled.copiedBuffer("Netty rocks!", CharsetUtil.UTF_8)); } /** *此方法會在接收到服務器數據後調用 * */ public void channelRead0(ChannelHandlerContext ctx, ByteBuf in) { System.out.println("Client received: " + ByteBufUtil.hexDump(in.readBytes(in.readableBytes()))); } /** *捕捉到異常 * */ public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { cause.printStackTrace(); ctx.close(); } }
其中需要注意的是channelRead0()方法,此方法接收到的可能是一些數據片段,比如服務器發送了5個字節數據,Client端不能保證一次全部收到,比如第一次收到3個字節,第二次收到2個字節。我們可能還會關心收到這些片段的順序是否可發送順序一致,這要看具體是什麼協議,比如基於TCP協議的字節流是能保證順序的。
還有一點,在Client端我們的業務Handler繼承的是SimpleChannelInboundHandler,而在服務器端繼承的是ChannelInboundHandlerAdapter,那麼這兩個有什麼區別呢?最主要的區別就是SimpleChannelInboundHandler在接收到數據後會自動release掉數據占用的Bytebuffer資源(自動調用Bytebuffer.release())。而為何服務器端不能用呢,因為我們想讓服務器把客戶端請求的數據發送回去,而服務器端有可能在channelRead方法返回前還沒有寫完數據,因此不能讓它自動release。
最後更新:2017-04-03 12:56:35