TCP分隔符和定长解码器

本文介绍了TCP上层协议如何区分消息,包括定长、分隔符结束、特殊分隔符和长度字段四种方式。重点讲解了DelimiterBasedFrameDecoder和FixedLengthFrameDecoder两种解码器的使用,提供了示例代码,帮助理解它们在处理分隔符和固定长度消息解码的过程。
摘要由CSDN通过智能技术生成

简介

​ TCP上层的协议通过四种方式对消息进行区分

  1. 消息长度固定,累计读取到长度总和为定长LEN的报文后,就认为读取到了一个完整的消息;将计数器置位,重新开始读取下一个数据报;
  2. 将回车换行符作为消息结束符,如FTP协议,这种方式在文本协议中应用比较广泛;
  3. 将特殊的分隔符作为消息的结束标志,回车换行符就是一种特殊的结束分隔符;
  4. 通过在消息头中定义长度字段来标识消息的总长度。

DelimiterBasedFrameDecoder

DelimiterBasedFrameDecoder可以自动完成以分隔符作为码流结束标识的消息的解码。

示例

DelimiterBasedFrameDecoderEchoServer

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package com.toughchow.io.netty.echoserver;

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.string.StringDecoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

/**
* Created by toughChow
* 2019-03-19 19:22
*/
public class DelimiterBasedFrameDecoderEchoServer {
public void bind(int port) throws Exception {
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.option(ChannelOption.SO_BACKLOG, 100)
.handler(new LoggingHandler(LogLevel.INFO))
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ByteBuf delimiter = Unpooled.copiedBuffer("$_".getBytes());
ch.pipeline().addLast(new DelimiterBasedFrameDecoder(1024, delimiter));
ch.pipeline().addLast(new StringDecoder());
ch.pipeline().addLast(new DelimiterBasedFrameDecoderEchoServerHandler());
}
});

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

f.channel().closeFuture().sync(); // 等待服务端监听端口关闭
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值