今天使用netty的固定长度进行解码
固定长度解码的原理就是按照指定消息的长度对消息自动解码。
在netty实现中,只需要采用FiexedLengthFrameDecoder解码器即可...
以下是服务端代码
1 package com.ming.netty.nio.stickpack; 2 3 4 5 import java.net.InetSocketAddress; 6 7 import io.netty.bootstrap.ServerBootstrap; 8 import io.netty.channel.ChannelFuture; 9 import io.netty.channel.ChannelInitializer; 10 import io.netty.channel.ChannelOption; 11 import io.netty.channel.EventLoopGroup; 12 import io.netty.channel.nio.NioEventLoopGroup; 13 import io.netty.channel.socket.SocketChannel; 14 import io.netty.channel.socket.nio.NioServerSocketChannel; 15 import io.netty.handler.codec.FixedLengthFrameDecoder; 16 import io.netty.handler.codec.string.StringDecoder; 17 import io.netty.handler.logging.LogLevel; 18 import io.netty.handler.logging.LoggingHandler; 19 20 public class EchoServer { 21 22 public void bind(String addr,int port) throws Exception{ 23 EventLoopGroup bossGroup=new NioEventLoopGroup(); 24 EventLoopGroup workGroup=new NioEventLoopGroup(); 25 try { 26 ServerBootstrap server=new ServerBootstrap(); 27 server.group(bossGroup,workGroup) 28 .channel(NioServerSocketChannel.class) 29 .option(ChannelOption.SO_BACKLOG, 100) 30 .handler(new LoggingHandler(LogLevel.INFO)) 31 .childHandler(new ChannelInitializer<SocketChannel>() { 32 33 @Override 34 protected void initChannel(SocketChannel sc) throws Exception { 35 sc.pipeline().addLast(new FixedLengthFrameDecoder(50));//FixedLengthFrameDecoder 这个类就是固定长度解码器,意思就是将消息指定长度进行解码 36 sc.pipeline().addLast(new StringDecoder()); 37 sc.pipeline().addLast(new EchoServerHandler()); 38 39 } 40 41 }); 42 ChannelFuture f=server.bind(new InetSocketAddress(addr, port)).sync(); 43 System.out.println("启动服务器:"+f.channel().localAddress()); 44 //等等服务器端监听端口关闭 45 f.channel().closeFuture().sync(); 46 } catch (Exception e) { 47 e.printStackTrace(); 48 }finally{ 49 bossGroup.shutdownGracefully(); 50 workGroup.shutdownGracefully(); 51 } 52 } 53 54 55 public static void main(String[] args) throws Exception{ 56 new EchoServer().bind("192.168.1.108", 8500); 57 } 58 59 }
1 package com.ming.netty.nio.stickpack; 2 3 import io.netty.buffer.ByteBuf; 4 import io.netty.buffer.Unpooled; 5 import io.netty.channel.ChannelHandlerAdapter; 6 import io.netty.channel.ChannelHandlerContext; 7 8 public class EchoServerHandler extends ChannelHandlerAdapter{ 9 10 int count=0; 11 12 @Override 13 public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { 14 15 String body=(String)msg; 16 System.out.println("服务器收到"+(++count)+"次客户端消息,消息是:"+body); 17 body+="$_"; 18 ByteBuf rep=Unpooled.copiedBuffer(body.getBytes()); 19 ctx.writeAndFlush(rep); 20 } 21 22 @Override 23 public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { 24 cause.printStackTrace(); 25 ctx.close(); 26 } 27 28 29 }
注意: FixedLengthFrameDecoder 这个类解码后,你客户端每次就会按照指定长度进行数据接收了,哈哈...例子中是50个长度的字符哈...
天天学习,天天进步。。。。。。
觉得不错点个赞吧...
时间: 2024-12-24 00:51:08