Netty學習之路(六)-分隔符和定長解碼器的應用
阿新 • • 發佈:2018-12-05
之前已經使用了LineBasedFrameDecoder解決TCP粘包問題,現在再學兩種解決TCP粘包的方法。
- DelimiterBasedFrameDecoder:可以自動完成以分隔符做結束標誌的訊息的解碼,分隔符自定義。
- FixedLengthFrameDecoder: 固定長度解碼器,它能夠按照指定的長度對訊息進行自動解碼,開發者不需要考慮TCP的粘包/拆包問題
DelimiterBasedFrameDecoder編碼實踐
與之前LineBaseFrameDecoder的使用一樣,只要將DelimiterBasedFrameDecoder和StringDecoder新增到服務端和客戶端的ChannelPipeline中。
服務端
package com.ph.Netty; import io.netty.bootstrap.ServerBootstrap; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.*; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.handler.codec.DelimiterBasedFrameDecoder; import io.netty.handler.codec.string.StringDecoder; /** * Create by PH on 2018/11/6 */ public class NettyServer { public static void main(String[] args) throws Exception { int port = 8080; if(args !=null && args.length>0) { try { port = Integer.valueOf(args[0]); }catch (NumberFormatException e) { //採用預設值 } } new NettyServer().bind(port); } public void bind(int port) throws Exception{ //NioEventLoopGroup是一個執行緒組,包含了一組NIO執行緒,專門用於網路事件的處理,實際上他們就是Reactor執行緒組 //bossGroup僅接收客戶端連線,不做複雜的邏輯處理,為了儘可能減少資源的佔用,取值越小越好 EventLoopGroup bossGroup = new NioEventLoopGroup(1); //用於進行SocketChannel的網路讀寫 EventLoopGroup workerGroup = new NioEventLoopGroup(); try { //是Netty用於啟動NIO服務端的輔助啟動類,目的是降低服務端的開發複雜度 ServerBootstrap b = new ServerBootstrap(); //配置NIO服務端 b.group(bossGroup, workerGroup) //指定使用NioServerSocketChannel產生一個Channel用來接收連線,他的功能對應於JDK // NIO類庫中的ServerSocketChannel類。 .channel(NioServerSocketChannel.class) //BACKLOG用於構造服務端套接字ServerSocket物件,標識當伺服器請求處理執行緒全滿時, // 用於臨時存放已完成三次握手的請求的佇列的最大長度。如果未設定或所設定的值小於1, // Java將使用預設值50。 .option(ChannelOption.SO_BACKLOG, 1024) //繫結I/O事件處理類,作用類似於Reactor模式中的Handler類,主要用於處理網路I/O事件 .childHandler(new ChannelInitializer<SocketChannel>() { protected void initChannel(SocketChannel arg0) throws Exception { //定義分隔符為"#_" ByteBuf delimiter = Unpooled.copiedBuffer("#_".getBytes()); //新增分隔符解碼器,第一個引數表示單條訊息最大長度,第二個引數是分隔符緩衝物件 arg0.pipeline().addLast(new DelimiterBasedFrameDecoder(1024, delimiter)); arg0.pipeline().addLast(new StringDecoder()); arg0.pipeline().addLast(new ServerHandler()); } }); //繫結埠,同步等待繫結操作完成,完成後返回一個ChannelFuture,用於非同步操作的通知回撥 ChannelFuture f = b.bind(port).sync(); //等待服務端監聽埠關閉之後才退出main函式 f.channel().closeFuture().sync(); } finally { //退出,釋放執行緒池資源 bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } } } /** * ChannelInboundHandlerAdapter實現自ChannelInboundHandler * ChannelInboundHandler提供了不同的事件處理方法你可以重寫 */ class ServerHandler extends ChannelInboundHandlerAdapter { private int count = 0; /** * 接受客戶端傳送的訊息 * @param ctx * @param msg * @throws Exception */ public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { //拿到的msg已經是解碼成字串之後的應答訊息了 String body = (String)msg; ++count; System.out.println("Server receive: " + body + count); //獲得ByteBuf型別的資料 ByteBuf resp = Unpooled.copiedBuffer(("Server message #_").getBytes()); //向客戶端傳送訊息,不直接將訊息寫入SocketChannel中,只是把待發送的訊息放到傳送快取陣列中, //再通過呼叫flush方法將緩衝區中的訊息全部寫到SocketChannel中 ctx.write(resp); } public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { //將訊息傳送佇列中的訊息寫入到SocketChannel中傳送給對方 ctx.flush(); } public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { //當發生異常時釋放資源 ctx.close(); } }
客戶端
package com.ph.Netty; import io.netty.bootstrap.Bootstrap; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.*; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioSocketChannel; import io.netty.handler.codec.DelimiterBasedFrameDecoder; import io.netty.handler.codec.string.StringDecoder; /** * Create by PH on 2018/11/6 */ public class NettyClient { public static void main(String[] args) throws Exception { int port = 8080; if (args != null && args.length > 0) { try { port = Integer.valueOf(args[0]); } catch (NumberFormatException e) { //採用預設值 } } new NettyClient().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>() { public void initChannel(SocketChannel ch) throws Exception{ //定義分隔符為"#_" ByteBuf delimiter = Unpooled.copiedBuffer("#_".getBytes()); //新增分隔符解碼器,第一個引數表示單條訊息最大長度,第二個引數是分隔符緩衝物件 ch.pipeline().addLast(new DelimiterBasedFrameDecoder(1024, delimiter)); ch.pipeline().addLast(new StringDecoder()); ch.pipeline().addLast(new ClientHandler()); } }); //發起非同步連線操作 ChannelFuture f = b.connect(host, port).sync(); //等待客戶端鏈路關閉 f.channel().closeFuture().sync(); }finally { group.shutdownGracefully(); } } } class ClientHandler extends ChannelInboundHandlerAdapter { private ByteBuf msg; private int count = 0; private byte[] req; public ClientHandler() { req = ("Client message " + "#_").getBytes(); } /** * 當客戶端和服務端TCP鏈路建立成功之後,Netty的NIO執行緒會呼叫此方法 * @param ctx */ public void channelActive(ChannelHandlerContext ctx) { //傳送訊息到服務端 for (int i=0;i<10;i++) { msg = Unpooled.buffer(req.length); msg.writeBytes(req); ctx.writeAndFlush(msg); } } public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception{ //StringDecoder已經將ByteBuf的訊息轉換成字串,msg已經是解碼成字串之後的應答訊息了。 String body = (String)msg; System.out.println("Client receive :" + body + ", the counter is:" + String.valueOf(++count)); } public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { ctx.close(); } }
在DelimiterBasedFrameDecoder的使用中,要注意的是在建立其物件時的引數,第一個引數表示單條訊息的最大長度,當達到該長度後仍然沒有查詢到分隔符,就丟擲TooLongFrameException異常,防止由於異常碼流缺失分隔符號導致的記憶體溢位;第二個引數就是分隔符緩衝物件。
FixedlengthFrameDecoder編碼實踐
由於與之前程式碼類似,這裡就貼一部分
protected void initChannel(SocketChannel arg0) throws Exception {
//定義分隔符為"#_"
//ByteBuf delimiter = Unpooled.copiedBuffer("#_".getBytes());
//新增分隔符解碼器
//arg0.pipeline().addLast(new DelimiterBasedFrameDecoder(1024, delimiter));
arg0.pipeline().addLast(new FixedLengthFrameDecoder(20));
arg0.pipeline().addLast(new StringDecoder());
arg0.pipeline().addLast(new ServerHandler());
}