您的位置:首页 > 理论基础 > 计算机网络

Netty学习之固定长度解码器解决TCP粘包

2016-04-24 16:32 579 查看

一.FixedLengthFrameDecoder

FixedLengthFrameDecoder是固定长度解码器,它能够按照指定长度的长度对消息进行自动解码,开发者不需要考虑TCP粘包/拆包问题,非常实用。

二.FixedLengthFrameDecoder应用开发

1.服务器类

package com.phei.netty.s2016042401;

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.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
/**
* 服务端
* @author renhj
*
*/
public class TimeServer {

public void bind(int port) throws Exception{

//第一个用户服务器接收客户端的连接
EventLoopGroup bossGroup = new NioEventLoopGroup();
//第二个用户SocketChannel的网络读写
EventLoopGroup workerGroup = new NioEventLoopGroup();
try{
//创建ServerBootstrap对象,启动 NIO服务端的辅助启动类
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup).
//设置为NIO
channel(NioServerSocketChannel.class)
.option(ChannelOption.SO_BACKLOG, 1024)
.handler(new LoggingHandler(LogLevel.INFO))
.childHandler(new ChildChannelHandler());

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

//等待服务器监听端口关闭
f.channel().closeFuture().sync();

}finally{
//释放线程池资源
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}

}

private class ChildChannelHandler extends ChannelInitializer<SocketChannel>{

@Override
protected void initChannel(SocketChannel arg0) throws Exception {
//解决TCP粘包问题,设置固定长度16字节的解码器
arg0.pipeline().addLast(new FixedLengthFrameDecoder(16));
arg0.pipeline().addLast(new StringDecoder());

arg0.pipeline().addLast(new TimeServerHandler());

}
}

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

int port = 8080;
if(args != null && args.length>0){
try{
port = Integer.valueOf(args[0]);
}catch(Exception e){
//采用默认值
}
}
new TimeServer().bind(port);
}

}


2.服务器核心处理类

package com.phei.netty.s2016042401;

import java.util.Date;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
/**
* 服务端核心处理类
* @author renhj
*
*/
public class TimeServerHandler extends ChannelHandlerAdapter {

private int counter;

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

String body = (String)msg;
System.out.println("The time server receive order :"+ body+" ; the counter is :"+ ++counter);
String currentTime = "QUERY TIME ORDER".equalsIgnoreCase(body)?
new Date(System.currentTimeMillis()).toString():"BAD ORDER";
currentTime = currentTime +System.getProperty("line.separator");
ByteBuf resp = Unpooled.copiedBuffer(currentTime.getBytes());
ctx.writeAndFlush(resp);
}

@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
ctx.flush();
}

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

}


3.客户端类

package com.phei.netty.s2016042401;

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

/**
* 客服端
* @author renhj
*
*/

public class TimeClient {

public void connect(int port , String host) throws Exception{

//配置客户端NIO线程组
EventLoopGroup group = new NioEventLoopGroup();
try{
Bootstrap b = new Bootstrap();
b.group(group).channel(NioSocketChannel.class)
.option(ChannelOption.TCP_NODELAY, true)
.handler(new ChannelInitializer<SocketChannel>(){

@Override
public void initChannel(SocketChannel ch) throws Exception{
//解决TCP粘包问题,设置固定长度30字节的解码器
ch.pipeline().addLast(new FixedLengthFrameDecoder(30));
ch.pipeline().addLast(new StringDecoder());
ch.pipeline().addLast(new TimeClientHandler());
}
});
//发起异步连接操作
ChannelFuture f = b.connect(host, port).sync();

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

}finally{
//释放NIO线程
group.shutdownGracefully();
}

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

int port = 8080;
if(args !=null && args.length>0){
try{
port = Integer.valueOf(args[0]);
}catch(Exception e){

}
}
new TimeClient().connect(port, "127.0.0.1");
}
}


4.客户端核心处理类

package com.phei.netty.s2016042401;

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

/**
* 客户端核心处理类
* @author renhj
*
*/
public class TimeClientHandler extends ChannelHandlerAdapter {

private int counter;
private byte[] req;

public TimeClientHandler(){
req  = ("QUERY TIME ORDER").getBytes();

}

@Override
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);
}
}

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

String body =  (String)msg;
System.out.println("Now is : "+body +" ; the counter is : "+ ++counter);

}

@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {

//释放资源
ctx.close();
}

}


5.运行结果



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: