netty DelimiterBasedFrameDecoder
netty server
EchoServer
package com.zhaowb.netty.ch5_1; 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; public class EchoServer { public void bind(int port) throws Exception { // 配置 服务端的 NIO 线程组
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup(); try {
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.option(ChannelOption.SO_BACKLOG, 1024)
.handler(new LoggingHandler(LogLevel.INFO))
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ByteBuf delimiter = Unpooled.copiedBuffer("$_".getBytes());// 创建分隔符对象 ByteBuf 使用 $_ 作为分隔符。 // 第一个参数为单条消息的最大长度,当达到该长度后仍然没有查找到分隔符,就抛出 TooLongFrameException 异常
// 防止由于异常码流缺失分隔符导致的内存溢出,这是 netty 解码器的可靠性保护;第二个参数是分隔符缓冲对象。
ch.pipeline().addLast(new DelimiterBasedFrameDecoder(1024, delimiter));
ch.pipeline().addLast(new StringDecoder());
ch.pipeline().addLast(new EchoServerHandler());
}
}); // 绑定端口,同步等待成功。
ChannelFuture f = b.bind(port).sync();
// 等待服务端监听端口关闭。
f.channel().closeFuture().sync();
} catch (Exception e) {
// 退出,释放线程池资源
bossGroup.shutdownGracefully();
workerGroup.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 (NumberFormatException e) {
}
}
new EchoServer().bind(port);
}
}
EchoServerHandler
package com.zhaowb.netty.ch5_1; import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext; public class EchoServerHandler extends ChannelHandlerAdapter { int counter = 0; @Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
System.out.println("链接成功!");
} @Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { // 当读取信息时,先经过 DelimiterBasedFrameDecoder 去掉结束分隔符,然后再使用 StringDecoder 将 ByteBuf 解码成字符串/
// 然后 EchoServerHandler 收到的数据就是解码后的字符串对象 String body = (String) msg;
System.out.println("This is " + ++counter + " times receive client : [" + body + "]");
body += "$_"; // 由于 设置 DelimiterBasedFrameDecoder 过滤掉了分隔符,返回给客户端时需要在消息的尾部拼接 "$_" ByteBuf echo = Unpooled.copiedBuffer(body.getBytes());
ctx.writeAndFlush(echo);
} @Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
ctx.close();// 发生异常,关闭链路
}
}
netty client
EchoClient
package com.zhaowb.netty.ch5_1; 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.string.StringDecoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler; public class EchoClient { 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
protected void initChannel(SocketChannel ch) throws Exception {
ByteBuf delimiter = Unpooled.copiedBuffer("$_".getBytes());// 创建分隔符对象 ByteBuf 使用 $_ 作为分隔符。
ch.pipeline().addLast(new DelimiterBasedFrameDecoder(1024, delimiter));
ch.pipeline().addLast(new StringDecoder());
ch.pipeline().addLast(new EchoClientHandler());
}
});
// 发起异步连接操作
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 (NumberFormatException e) {
}
}
new EchoClient().connect(port, "127.0.0.1");
}
}
EchoClientHandler
package com.zhaowb.netty.ch5_1; import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext; public class EchoClientHandler extends ChannelHandlerAdapter { private int counter; static final String ECHO_REQ = "hello.$_"; public EchoClientHandler() {
} @Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
System.out.println("链接成功!");
for (int i = 0; i < 10; i++) {
ctx.writeAndFlush(Unpooled.copiedBuffer(ECHO_REQ.getBytes()));
}
} @Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { System.out.println("This is " + ++counter + "times receive server : [" + msg.toString() + "]");
} @Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
ctx.flush();
} @Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
ctx.close();
}
}
如果sever 没有 ch.pipeline().addLast(new DelimiterBasedFrameDecoder(1024, delimiter));
,在接受数据的时候会一起接收到客户端发送的所有数据,造成粘包问题。如果要使用ch.pipeline().addLast(new FixedLengthFrameDecoder(20));
就是截取固定长度的信息,超过的不会输出。
https://gitee.com/JiShiMoWang_admin/netty-learning
https://github.com/zhaowenbo1234/netty
netty DelimiterBasedFrameDecoder的更多相关文章
- Netty学习(五)-DelimiterBasedFrameDecoder
上一节我们说了LineBasedframeDecoder来解决粘包拆包的问题,TCP以流的方式进行数据传输,上层应用协议为了对消息进行区分,一般采用如下4种方式: 消息长度固定,累计读取到消息长度总和 ...
- netty: 解决粘包拆包: 分隔符DelimiterBasedFrameDecoder,定长消息FixedLengthFrameDecoder
DelimiterBasedFrameDecoder 自定义分隔符 给Server发送多条信息,但是server会讲多条信息合并为一条.这时候我们需要对发生的消息指定分割,让client和server ...
- Netty源码分析之客户端启动过程
一.先来看一下客户端示例代码. public class NettyClientTest { public void connect(int port, String host) throws Exc ...
- Netty源码分析之服务端启动过程
一.首先来看一段服务端的示例代码: public class NettyTestServer { public void bind(int port) throws Exception{ EventL ...
- Netty 实现聊天功能
Netty 是一个 Java NIO 客户端服务器框架,使用它可以快速简单地开发网络应用程序,比如服务器和客户端的协议.Netty 大大简化了网络程序的开发过程比如 TCP 和 UDP 的 socke ...
- Netty(四)分隔符与定长解码器的使用
TCP以流的形式进行数据传输,上层的应用协议为了对消息进行划分,往往采用如下的4种方式. (1)消息长度固定,累计读到长度总和为定长len的报文后,就认为读取到了一个完整的消息:然后重新开始读取下一个 ...
- 基于Java Netty框架构建高性能的部标808协议的GPS服务器
使用Java语言开发一个高质量和高性能的jt808 协议的GPS通信服务器,并不是一件简单容易的事情,开发出来一段程序和能够承受数十万台车载接入是两码事,除去开发部标808协议的固有复杂性和几个月长周 ...
- netty 解决TCP粘包与拆包问题(二)
TCP以流的方式进行数据传输,上层应用协议为了对消息的区分,采用了以下几种方法. 1.消息固定长度 2.第一篇讲的回车换行符形式 3.以特殊字符作为消息结束符的形式 4.通过消息头中定义长度字段来标识 ...
- Netty权威指南
Netty权威指南(异步非阻塞通信领域的经典之作,国内首本深入剖析Netty的著作,全面系统讲解原理.实战和源码,带你完美进阶Netty工程师.) 李林锋 著 ISBN 978-7-121-233 ...
随机推荐
- thinkphp 原生分页
paginate() 是有三个参数: 第一个参数是 $listRows [int],也就是当前的页数 第二个参数是 $simple [boolean], 是否简洁模式或者总记录数 第三个参数是 $co ...
- 陈云pytorch学习笔记_用50行代码搭建ResNet
import torch as t import torch.nn as nn import torch.nn.functional as F from torchvision import mode ...
- NX二次开发-UFUN多选菜单对话框uc1605
NX11+VS2013 #include <uf.h> #include <uf_ui.h> UF_initialize(); //多选菜单对话框 char sPromptSt ...
- Notepad++如何对比文件 Notepad++对比两个文件代码方法
大家在使用Notepad++的时候,需要对编辑的两个文件进行比较,找出两个文件代码的区别,快速进行编辑修改,那么Notepad++如何对比文件,下面小编就给大家带来Notepad++对比两个文件代码方 ...
- scrollReveal.js导致页面加载完之后页面中点击事件添加的css参数失效了(我的Hexo next博客引发的问题)
文章目录 时间 背景 问题解决 个人博客:https://mmmmmm.me 源码:https://github.com/dataiyangu/dataiyangu.github.io 时间 2019 ...
- Codeforce 1175A From Hero to Zero
题目链接:http://codeforces.com/problemset/problem/1175/A AC代码: #include<cstdio> #include<iostre ...
- 关于DEBUG的一点体会
目录 1. 看待问题 2. 为什么要debug 3. 我理解的问题定位能力 4. debug能力模型的4个层级 5. 小结与扩展 1. 看待问题 遇到更高级的bug,解决更重要的问题,是开发同学的迭代 ...
- svn更新的时候断电,下次在更新出现svn: sqlite: database disk image is malformed
svn更新的时候断电,下次在更新出现svn: sqlite: database disk image is malformed 这种悲催的事情竟然发生了 解决办法:
- 榨取kkksc03
题目描述 洛谷的运营组决定,如果一名oier向他的教练推荐洛谷,并能够成功的使用(成功使用的定义是:该团队有20个或以上的成员,上传10道以上的私有题目,布置过一次作业并成功举办过一次公开比赛),那么 ...
- Linux服务器下对Oracle数据库expdp(导出)和impdp(导入)
紧接上篇文章,Oracle数据库架构已经创建完成,我的需求是:将老服务器上的数据库迁移到新的数据库上. 这就用到impdp(导入)操作. 要想实现对新数据库的impdp(导入)工作, 首先需要从老的数 ...