很久没更新了,先吐槽一下,最近太忙了,不知道为啥到了年末居然这么忙,最可气的是最近一个项目遇到一个很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); } }