Netty解决粘包问题(2) 定长填充

来源:互联网 发布:韩氏父子 圆号网络 编辑:程序博客网 时间:2024/05/21 10:22
第二种解决粘包的方案,就是每次发送固定长度的数据包,如果长度不够,那就用空字符串填充

import java.nio.ByteBuffer;import io.netty.bootstrap.ServerBootstrap;import io.netty.buffer.ByteBuf;import io.netty.buffer.Unpooled;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.DelimiterBasedFrameDecoder;import io.netty.handler.codec.FixedLengthFrameDecoder;import io.netty.handler.codec.string.StringDecoder;import io.netty.handler.codec.string.StringEncoder;public class Server {    public static void main(String[] args) throws Exception{        //1 创建2个线程,一个是负责接收客户端的连接。一个是负责进行数据传输的        EventLoopGroup pGroup = new NioEventLoopGroup();        EventLoopGroup cGroup = new NioEventLoopGroup();        //2 创建服务器辅助类        ServerBootstrap b = new ServerBootstrap();        b.group(pGroup, cGroup)         .channel(NioServerSocketChannel.class)         .option(ChannelOption.SO_BACKLOG, 1024)         .option(ChannelOption.SO_SNDBUF, 32*1024)         .option(ChannelOption.SO_RCVBUF, 32*1024)         .childHandler(new ChannelInitializer<SocketChannel>() {            @Override            protected void initChannel(SocketChannel sc) throws Exception {                //设置定长字符串接收                sc.pipeline().addLast(new FixedLengthFrameDecoder(5));                //设置字符串形式的解码                sc.pipeline().addLast(new StringDecoder());                sc.pipeline().addLast(new ServerHandler());            }        });        //4 绑定连接        ChannelFuture cf = b.bind(8765).sync();        //等待服务器监听端口关闭        cf.channel().closeFuture().sync();        pGroup.shutdownGracefully();        cGroup.shutdownGracefully();    }}

import io.netty.buffer.Unpooled;import io.netty.channel.ChannelHandlerAdapter;import io.netty.channel.ChannelHandlerContext;public class ServerHandler extends ChannelHandlerAdapter {    @Override    public void channelActive(ChannelHandlerContext ctx) throws Exception {        System.out.println(" server channel active... ");    }    @Override    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {        String request = (String)msg;        System.out.println("Server :" + msg);        String response =  request ;        ctx.writeAndFlush(Unpooled.copiedBuffer(response.getBytes()));    }    @Override    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {    }    @Override    public void exceptionCaught(ChannelHandlerContext ctx, Throwable t) throws Exception {    }}

import io.netty.bootstrap.Bootstrap;import io.netty.buffer.ByteBuf;import io.netty.buffer.Unpooled;import io.netty.channel.ChannelFuture;import io.netty.channel.ChannelInitializer;import io.netty.channel.EventLoopGroup;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.FixedLengthFrameDecoder;import io.netty.handler.codec.string.StringDecoder;import io.netty.handler.codec.string.StringEncoder;public class Client {    public static void main(String[] args) throws Exception {        EventLoopGroup group = new NioEventLoopGroup();        Bootstrap b = new Bootstrap();        b.group(group)         .channel(NioSocketChannel.class)         .handler(new ChannelInitializer<SocketChannel>() {            @Override            protected void initChannel(SocketChannel sc) throws Exception {                sc.pipeline().addLast(new FixedLengthFrameDecoder(5));                sc.pipeline().addLast(new StringDecoder());                sc.pipeline().addLast(new ClientHandler());            }        });        ChannelFuture cf = b.connect("127.0.0.1", 8765).sync();        cf.channel().writeAndFlush(Unpooled.wrappedBuffer("aaaaabbbbb".getBytes()));        cf.channel().writeAndFlush(Unpooled.copiedBuffer("ccccccc".getBytes()));        //等待客户端端口关闭        cf.channel().closeFuture().sync();        group.shutdownGracefully();    }}

import io.netty.channel.ChannelHandlerAdapter;import io.netty.channel.ChannelHandlerContext;public class ClientHandler extends ChannelHandlerAdapter{    @Override    public void channelActive(ChannelHandlerContext ctx) throws Exception {        System.out.println("client channel active... ");    }    @Override    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {        String response = (String)msg;        System.out.println("Client: " + response);    }    @Override    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {    }    @Override    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {    }}

运行结果
//服务器端server channel active... Server :aaaaaServer :bbbbbServer :ccccc

//客户端client channel active... Client: aaaaaClient: bbbbbClient: ccccc
0 0
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 域名已被注册了怎么办 腿上皮肤干燥像鱼鳞怎么办 货拉拉抢不到单怎么办 京东优惠券删了怎么办 吃了发黄的大米怎么办 误吃了霉味大米怎么办 吃了发霉的食物怎么办 面包发霉了吃了怎么办 长期吃了地沟油怎么办 吃了地沟油呕吐怎么办 dnf冲到别人账号怎么办 皮肤买错大区了怎么办 微信实名超过5个怎么办 微信绑定超过5个怎么办 300英雄忘了账号怎么办 163邮箱登陆不上怎么办 手机收不到微信怎么办 苹果微信反应慢怎么办 微信网速特别慢怎么办 微信突然卡住了怎么办 微信一直卡死怎么办 微信打开卡了怎么办 微信卡住不动了怎么办 微信突然卡死了怎么办 手机京东e卡使用怎么办 携程礼品卡欺诈,怎么办 携程礼品卡诈骗怎么办 易事通卡过期了怎么办 设备被淘宝黑了怎么办 饭店排风噪音大怎么办 善融商城不发货怎么办 ps渲染图像很慢怎么办 买房子收据丢了怎么办 买房子发票丢了怎么办 买房的收据丢了怎么办 首付款收据丢了怎么办 预购房收据丢了怎么办 陆金所取现不了怎么办 买了一条假烟怎么办 微商收钱不发货怎么办 微信红包收不到怎么办