很久沒更新了,先吐槽一下,最近太忙了,不知道爲啥到了年末居然這麼忙,最可氣的是最近一個項目遇到一個很2的產品還有一個很2的測試,測試是一問三不知,怎麼測都要來問我,產品說這個東西我以爲很簡單啊,怎麼你作的這麼複雜,讓我講給他聽,我講了1/4,他就矇蔽了,說了句這麼複雜啊。。。。。。哎,懷念在支付寶的日子啊。。。。。不過想一想在這兒也待不了多久了,也就算了吧。哎,跑題了,今天給你們繼續講一下Netty,此次介紹一個新的解碼器:固定長度的編解碼器,聽名字就很好理解,說白了就是按照數據幀的長短來肯定一幀。比方說這麼一個數據幀:hello alipay,若是設置長度爲5那麼服務端在接收後就會獲得如下幾幀:hello,空格alip,ay。直接上代碼。java
服務端代碼:bootstrap
package com.dlb.note.server; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.*; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.handler.codec.FixedLengthFrameDecoder; import io.netty.handler.codec.string.StringDecoder; import java.nio.charset.Charset; /** * 功能:固定長度解碼器時間服務器 * 版本:1.0 * 日期:2016/12/9 16:22 * 做者:馟蘇 */ public class FixLengthFrameDecoderTimeServer { /** * main函數 * @param args */ public static void main(String []args) { // 構造nio線程組 EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workGroup = new NioEventLoopGroup(); try { ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.group(bossGroup, workGroup) .channel(NioServerSocketChannel.class) .option(ChannelOption.SO_BACKLOG, 1024) .childHandler(new ChannelInitializer() { protected void initChannel(Channel channel) throws Exception { // 固定長度的解碼器 channel.pipeline().addLast(new FixedLengthFrameDecoder(20)); // 將字節對象轉換爲字符串 channel.pipeline().addLast(new StringDecoder(Charset.forName("UTF-8"))); channel.pipeline().addLast(new MyFixHandler()); } }); // 綁定端口,同步等待成功 ChannelFuture future = bootstrap.bind(8888).sync(); System.out.println("----服務端在8888端口監聽----"); // 等待服務端監聽端口關閉 future.channel().closeFuture().sync(); } catch (Exception e) { e.printStackTrace(); } finally { // 優雅的退出,釋放線程池資源 bossGroup.shutdownGracefully(); workGroup.shutdownGracefully(); } } } class MyFixHandler extends ChannelHandlerAdapter { // 客戶端連接異常 @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { System.out.println("client exception,ip=" + ctx.channel().remoteAddress()); ctx.close(); super.exceptionCaught(ctx, cause); } // 客戶端連接到來 @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { System.out.println("client come,ip=" + ctx.channel().remoteAddress()); super.channelActive(ctx); } // 客戶端連接關閉 @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { System.out.println("client close,ip=" + ctx.channel().remoteAddress()); ctx.close(); super.channelInactive(ctx); } // 可讀 @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { String req = (String) msg; System.out.println(req); super.channelRead(ctx, msg); } }