在TCP协议中我们知道当我们在接收消息时候,我们如何判断我们一次读取到的包就是整包消息呢,特别是对于使用了长连接和使用了非阻塞I/O的程序。上节我们也说了上层应用协议为了对消息进行区分一般采用4种方式。前面三种我们都说了,第四种是:通过在消息头定义长度字段来标识消息总长度。这个我们还没讲。当然Netty也提供了相应的解码器:LengthFieldBasedFrameDecoder。
大多数的协议(私有或者公有),协议头中会携带长度字段,用于标识消息体或者整包消息的长度,例如SMPP、HTTP协议等。由于基于长度解码需求 的通用性,Netty提供了LengthFieldBasedFrameDecoder,自动屏蔽TCP底层的拆包和粘 包问题,只需要传入正确的参数,即可轻松解决“读半包“问题。
我们先来看一下他的构造函数:
public LengthFieldBasedFrameDecoder(ByteOrder byteOrder,
int maxFrameLength,
int lengthFieldOffset,
int lengthFieldLength,
int lengthAdjustment,
int initialBytesToStrip,
boolean failFast) {
}
LengthFieldBasedFrameDecoder定义了一个长度的字段来表示消息的长度,因此能够处理可变长度的消息。将消息分为消息头和消息体,消息头固定位置增加一个表示长度的字段,通过长度字段来获取整包的信息。LengthFieldBasedFrameDecoder继承了ByteToMessageDecoder,即转换字节这样的工作是由ByteToMessageDecoder来完成,而LengthFieldBasedFrameDecoder只用安心完成他的解码工作就好。Netty在解耦和方面确实做的不错。
既然我们知道了LengthFieldBasedFrameDecoder处理的是带有消息头和消息体的消息类型,那么我们完全可以来定义一个我们自己的消息,我们来写一个消息类:
public class Message {
//消息类型
private byte type;
//消息长度
private int length;
//消息体
private String msgBody;
public Message(byte type, int length, String msgBody) {
this.type = type;
this.length = length;
this.msgBody = msgBody;
}
public byte getType() {
return type;
}
public void setType(byte type) {
this.type = type;
}
public int getLength() {
return length;
}
public void setLength(int length) {
this.length = length;
}
public String getMsgBody() {
return msgBody;
}
public void setMsgBody(String msgBody) {
this.msgBody = msgBody;
}
}
我们先来写服务端:
public class NewServer {
private static final int MAX_FRAME_LENGTH = 1024 * 1024;
private static final int LENGTH_FIELD_LENGTH = 4;
private static final int LENGTH_FIELD_OFFSET = 1;
private static final int LENGTH_ADJUSTMENT = 0;
private static final int INITIAL_BYTES_TO_STRIP = 0;
private int port;
public NewServer(int port) {
this.port = port;
}
public void start(){
EventLoopGroup bossGroup = new NioEventLoopGroup(1);
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap sbs = new ServerBootstrap()
.group(bossGroup,workerGroup)
.channel(NioServerSocketChannel.class)
.localAddress(new InetSocketAddress(port))
.childHandler(new NewServerChannelInitializer(MAX_FRAME_LENGTH,LENGTH_FIELD_LENGTH,LENGTH_FIELD_OFFSET,LENGTH_ADJUSTMENT,INITIAL_BYTES_TO_STRIP))
.option(ChannelOption.SO_BACKLOG, 128)
.childOption(ChannelOption.SO_KEEPALIVE, true);
ChannelFuture future = sbs.bind(port).sync();
System.out.println("Server start listen at " + port );
future.channel().closeFuture().sync();
} catch (Exception e) {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
public static void main(String[] args) {
NewServer server = new NewServer(7788);
server.start();
}
}
注意到服务端我们在上面定义了5个参数,这5个参数是为了传入LengthFieldBasedFrameDecoder里面用的,因为我们的LengthFieldBasedFrameDecoder写在了NewServerChannelInitializer类里面,所以这几个参数采用可配置的方式也更符合可扩展性,我们分别说一下这几个参数定值的含义:
然后我们写ChannelInitializer:
public class NewServerChannelInitializer extends ChannelInitializer<SocketChannel> {
private final int MAX_FRAME_LENGTH;
private final int LENGTH_FIELD_LENGTH;
private final int LENGTH_FIELD_OFFSET;
private final int LENGTH_ADJUSTMENT;
private final int INITIAL_BYTES_TO_STRIP;
public NewServerChannelInitializer(int MAX_FRAME_LENGTH, int LENGTH_FIELD_LENGTH, int LENGTH_FIELD_OFFSET, int LENGTH_ADJUSTMENT, int INITIAL_BYTES_TO_STRIP) {
this.MAX_FRAME_LENGTH = MAX_FRAME_LENGTH;
this.LENGTH_FIELD_LENGTH = LENGTH_FIELD_LENGTH;
this.LENGTH_FIELD_OFFSET = LENGTH_FIELD_OFFSET;
this.LENGTH_ADJUSTMENT = LENGTH_ADJUSTMENT;
this.INITIAL_BYTES_TO_STRIP = INITIAL_BYTES_TO_STRIP;
}
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
ChannelPipeline pipeline = socketChannel.pipeline();
pipeline.addLast(new NewDecoder(MAX_FRAME_LENGTH,LENGTH_FIELD_LENGTH,LENGTH_FIELD_OFFSET,LENGTH_ADJUSTMENT,INITIAL_BYTES_TO_STRIP,false));
// 自己的逻辑Handler
pipeline.addLast("handler", new NewServerHandler());
}
}
上面用到了我们自己写的Decoder,接下来定义一个Decoder,继承LengthFieldBasedFrameDecoder,以方便我们做一些改写:
public class NewDecoder extends LengthFieldBasedFrameDecoder {
/** * 我们在Message类中定义了type和length,这都放在消息头部 * type占1个字节,length占4个字节所以头部总长度是5个字节 */
private static final int HEADER_SIZE = 5;
private byte type;
private int length;
private String msgBody;
/** * * @param maxFrameLength 网络字节序,默认为大端字节序 * @param lengthFieldOffset 消息中长度字段偏移的字节数 * @param lengthFieldLength 数据帧的最大长度 * @param lengthAdjustment 该字段加长度字段等于数据帧的长度 * @param initialBytesToStrip 从数据帧中跳过的字节数 * @param failFast 如果为true,则表示读取到长度域,TA的值的超过maxFrameLength,就抛出一个 TooLongFrameException */
public NewDecoder(int maxFrameLength, int lengthFieldOffset,
int lengthFieldLength, int lengthAdjustment, int initialBytesToStrip,
boolean failFast) {
super(maxFrameLength, lengthFieldOffset, lengthFieldLength,
lengthAdjustment, initialBytesToStrip, failFast);
}
@Override
protected Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
if(in == null){
return null;
}
if(in.readableBytes() < HEADER_SIZE){
throw new Exception("错误的消息");
}
/** * 通过源码我们能看到在读的过程中 * 每读一次读过的字节即被抛弃 * 即指针会往前跳 */
type = in.readByte();
length = in.readByte();
if(in.readableBytes() < length){
throw new Exception("消息不正确");
}
ByteBuf buf = in.readBytes(length);
byte[] b = new byte[buf.readableBytes()];
buf.readBytes(b);
msgBody = new String(b,"UTF-8");
Message msg = new Message(type,length,msgBody);
return msg;
}
}
在上面的NewDecoder中有一个HEADER_SIZE-消息头。上面也解释过了,我们在Message中定义的type和length分别占一个字节和4个字节(别问我为啥是4个哈)。所以我们的消息头就是5个字节啦。
接下来就是服务端的handler了:
public class NewServerHandler extends SimpleChannelInboundHandler<Object> {
@Override
protected void channelRead0(ChannelHandlerContext channelHandlerContext, Object o) throws Exception {
if(o instanceof Message) {
Message msg = (Message)o;
System.out.println("Client->Server:"+channelHandlerContext.channel().remoteAddress()+" send "+msg.getMsgBody());
}
}
}
在handler中我们用来接收已经被NewDecoder解码过后的客户端发送过来的消息。
下面是客户端:
public class NewClient {
private int port;
private String address;
public NewClient(int port,String address) {
this.port = port;
this.address = address;
}
public void start(){
EventLoopGroup group = new NioEventLoopGroup();
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(group)
.channel(NioSocketChannel.class)
.option(ChannelOption.TCP_NODELAY, true)
.handler(new NewClientChannelInitializer());
try {
ChannelFuture future = bootstrap.connect(address,port).sync();
future.channel().closeFuture().sync();
} catch (Exception e) {
e.printStackTrace();
}finally {
group.shutdownGracefully();
}
}
public static void main(String[] args) {
NewClient client = new NewClient(7788,"127.0.0.1");
client.start();
}
}
客户端Initializer:
public class NewClientChannelInitializer extends ChannelInitializer<SocketChannel> {
protected void initChannel(SocketChannel socketChannel) throws Exception {
ChannelPipeline pipeline = socketChannel.pipeline();
pipeline.addLast(new NewEncoder());
pipeline.addLast(new NewClientHandler());
}
}
客户端中我们又定义了一个编码器NewEncoder,继承了MessageToByteEncoder,该类用于将文本信息转换为流:
public class NewEncoder extends MessageToByteEncoder<Message> {
@Override
protected void encode(ChannelHandlerContext channelHandlerContext, Message message, ByteBuf byteBuf) throws Exception {
if(message == null){
throw new Exception("未获得消息内容");
}
String msgBody = message.getMsgBody();
byte[] b = msgBody.getBytes(Charset.forName("utf-8"));
byteBuf.writeByte(message.getType());
byteBuf.writeByte(b.length);
byteBuf.writeBytes(b);
}
}
接下来是我们的客户端handler:
public class NewClientHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
String m = "你好啊,Netty。昂昂";
Message msg = new Message((byte)0xCA, m.length(), m);
ctx.writeAndFlush(msg);
}
}
注意到在handler中我们发送了一个Message对象。然后会由NewEncoder编码发送出去,服务端对消息解码获得消息头和消息体。分别启动服务端和客户端,打印结果为:
我们的消息就发送出去了。
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://blog.csdn.net/a953713428/article/details/68939371
内容来源于网络,如有侵权,请联系作者删除!