4、netty之解决tcp粘包问题(netty学习笔记)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u012727852/article/details/78087351
解决这个问题netty主要用到了:

1、LineBasedFrameDecoder  换行符解码器
2、DelimiterBasedFrameDecoder  自定义解析符解码器
3、FixedLengthFrameDecoder  定长报文解码器

4、StringDecoder


TimeClient

package com.play.netty.timeserver.client;

import io.netty.bootstrap.Bootstrap;
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.NioSocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;

/**
* 拆包、粘包
* Created by IntelliJ IDEA.
* User: GongQi
* Date: 2017/8/31
*/
public class TimeClient {

    public void connect(int port, String host) throws Exception {
        //建立客户端NIO线程组
        EventLoopGroup loopGroup = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(loopGroup)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.TCP_NODELAY, true)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(
                                    new LineBasedFrameDecoder(1024));
                            ch.pipeline().addLast(new StringDecoder());
                            ch.pipeline().addLast(new TimeClientHandler());
                        }
                    });

            //发起异步连接
            ChannelFuture channelFuture=b.connect(host,port).sync();

            System.out.println("连接成功");

            //等待客户端链路关闭
            channelFuture.channel().closeFuture().sync();

        } finally {
            loopGroup.shutdownGracefully();
        }

    }

    public static void main(String[] args) throws Exception {

            new TimeClient().connect(8180,"127.0.0.1");
    }
}
TimeClientHandler

package com.play.netty.timeserver.client;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

/**
* Created by IntelliJ IDEA.
* User: GongQi
* Date: 2017/8/31
*/
public class TimeClientHandler extends ChannelHandlerAdapter {

    private int count;

    private byte[] req;

    public TimeClientHandler() {
        req = ("SHOW_TIMEn"+System.getProperty("line.separator")).getBytes();
    }

    public void channelActive(ChannelHandlerContext ctx) throws Exception {

        ByteBuf message = null;
        for (int i = 0; i < 100; i++) {
            message = Unpooled.buffer(req.length);
            message.writeBytes(req);
            ctx.writeAndFlush(message);
        }
    }

    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        String body = (String) msg;
        System.out.println("now is : :" + body + "; the count is " + ++count);
        //

    }

    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("发生异常:" + cause.getMessage());
        ctx.close();
    }
}


TimeServer
package com.play.netty.timeserver.server;

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.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;

/**
* Created by IntelliJ IDEA.
* User: GongQi
* Date: 2017/8/31
*/
public class TimeServer {

    public void bind(Integer port) throws Exception {

        //配置服务端的NIO线程组
        EventLoopGroup bossGroup=new NioEventLoopGroup();
        EventLoopGroup workGroup=new NioEventLoopGroup();

        try{
            ServerBootstrap b=new ServerBootstrap();
            b.group(bossGroup,workGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG,1024)
                    .childHandler(new ChildChannelHandler());

            //同步等待绑定端口完成
            //
            ChannelFuture channelFuture=b.bind(port).sync();

            //阻塞,只有当服务端链路关闭后才退出
            channelFuture.channel().closeFuture().sync();

        }finally {
            bossGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
        }

    }

    private class ChildChannelHandler extends ChannelInitializer<SocketChannel>{
        protected void initChannel(SocketChannel arg0) throws Exception {
            arg0.pipeline().addLast(new LineBasedFrameDecoder(1024));
            arg0.pipeline().addLast(new StringDecoder());
            arg0.pipeline().addLast(new TimeServerHandler());
        }
    }

    public static void main(String[] args) throws Exception {
        int port=8180;
        new TimeServer().bind(port);
    }

}

TimeServerHandler

package com.play.netty.timeserver.server;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
* Created by IntelliJ IDEA.
* User: GongQi
* Date: 2017/8/31
*/
public class TimeServerHandler extends ChannelHandlerAdapter {

    private int counter;

    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        String body= (String) msg;
        System.out.println("this time server reserve order " + body+";  the counnt is "+ ++counter);
        //
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd hh:mm:ss");

        String currtime = "SHOW_TIME".equals(body) ? format.format(new Date()) : "BAD_CMD";

        currtime=currtime+System.getProperty("line.separator");
        ByteBuf resp = Unpooled.copiedBuffer(currtime.getBytes());
        ctx.writeAndFlush(resp);
    }

    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}


猜你喜欢

转载自blog.csdn.net/u012727852/article/details/78087351