netty 解决TCP粘包与拆包问题(三)

时间:2023-03-08 17:03:56

今天使用netty的固定长度进行解码

固定长度解码的原理就是按照指定消息的长度对消息自动解码。

在netty实现中,只需要采用FiexedLengthFrameDecoder解码器即可...

以下是服务端代码

 package com.ming.netty.nio.stickpack;

 import java.net.InetSocketAddress;

 import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
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 io.netty.handler.codec.FixedLengthFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler; public class EchoServer { public void bind(String addr,int port) throws Exception{
EventLoopGroup bossGroup=new NioEventLoopGroup();
EventLoopGroup workGroup=new NioEventLoopGroup();
try {
ServerBootstrap server=new ServerBootstrap();
server.group(bossGroup,workGroup)
.channel(NioServerSocketChannel.class)
.option(ChannelOption.SO_BACKLOG, 100)
.handler(new LoggingHandler(LogLevel.INFO))
.childHandler(new ChannelInitializer<SocketChannel>() { @Override
protected void initChannel(SocketChannel sc) throws Exception {
sc.pipeline().addLast(new FixedLengthFrameDecoder(50));//FixedLengthFrameDecoder 这个类就是固定长度解码器,意思就是将消息指定长度进行解码
sc.pipeline().addLast(new StringDecoder());
sc.pipeline().addLast(new EchoServerHandler()); } });
ChannelFuture f=server.bind(new InetSocketAddress(addr, port)).sync();
System.out.println("启动服务器:"+f.channel().localAddress());
//等等服务器端监听端口关闭
f.channel().closeFuture().sync();
} catch (Exception e) {
e.printStackTrace();
}finally{
bossGroup.shutdownGracefully();
workGroup.shutdownGracefully();
}
} public static void main(String[] args) throws Exception{
new EchoServer().bind("192.168.1.108", 8500);
} }
 package com.ming.netty.nio.stickpack;

 import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext; public class EchoServerHandler extends ChannelHandlerAdapter{ int count=0; @Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { String body=(String)msg;
System.out.println("服务器收到"+(++count)+"次客户端消息,消息是:"+body);
body+="$_";
ByteBuf rep=Unpooled.copiedBuffer(body.getBytes());
ctx.writeAndFlush(rep);
} @Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
ctx.close();
} }

注意: FixedLengthFrameDecoder 这个类解码后,你客户端每次就会按照指定长度进行数据接收了,哈哈...例子中是50个长度的字符哈...

天天学习,天天进步。。。。。。

觉得不错点个赞吧...