Java基础之《netty(28)—TCP粘包拆包原理》

news2024/10/5 21:26:04

一、基本介绍

1、TCP是面向连接的,面向流的,提供高可靠性服务。收发两端(客户端和服务器端)都要有一一成对的socket,因此,发送端为了将多个发给接收端的包,更有效的发给对方,使用了优化方法(Nagle算法),将多次间隔较小且数据量小的数据,合并成一个大的数据块,然后进行封包。这样做虽然提高了效率,但是接收端就难于分辨出完整的数据包了,因为面向流的通信是无消息保护边界的。

2、由于TCP无消息保护边界,需要在接收端处理消息边界问题,也就是我们所说的粘包、拆包问题。

3、TCP粘包、拆包图解
假设客户端分别发送了两个数据包D1和D2给服务端,由于服务端一次读取到字节数是不确定的,故可能存在以下四种情况。
(1)服务端分两次读取到了两个独立的数据包,分别是D1和D2,没有粘包和拆包。
(2)服务端一次接收到了两个数据包,D1和D2粘合在一起,称之为TCP粘包。
(3)服务端分两次读取到了数据包,第一次读取到了完整的D1包和D2包的部分内容,第二次读取到了D2包的剩余内容,这称之为TCP拆包。
(4)服务端分两次读取到了数据包,第一次读取到了D1包的部分内容,第二次读取到了D1包的剩余部分内容和完整的D2包。

二、TCP粘包和拆包现象实例

1、在编写netty程序时,如果没有做处理,就会发生粘包和拆包的问题

2、服务端
NettyServer.java

package netty.tcpStickPackage;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

public class NettyServer {
	public static void main(String[] args) {
		
		EventLoopGroup bossGroup = new NioEventLoopGroup(1);
		EventLoopGroup workerGroup = new NioEventLoopGroup(8);
		
		try {
			ServerBootstrap bootstrap = new ServerBootstrap();
			bootstrap.group(bossGroup, workerGroup)
				.channel(NioServerSocketChannel.class)
				.handler(new LoggingHandler(LogLevel.DEBUG))
				.childHandler(new NettyServerInitializer()); //自定义一个初始化类
			
			ChannelFuture cf = bootstrap.bind(7000).sync();
			cf.channel().closeFuture().sync();
			
		} catch (Exception e) {
			e.printStackTrace();
			
		} finally {
			bossGroup.shutdownGracefully();
			workerGroup.shutdownGracefully();
		}
	}
}

NettyServerInitializer.java

package netty.tcpStickPackage;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;

public class NettyServerInitializer extends ChannelInitializer<SocketChannel> {

	@Override
	protected void initChannel(SocketChannel ch) throws Exception {
		ChannelPipeline pipeline = ch.pipeline();
		//加入一个自定义handler
		pipeline.addLast(new NettyChannelHandler());
	}

}

NettyChannelHandler.java

package netty.tcpStickPackage;

import java.util.UUID;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;

public class NettyChannelHandler extends SimpleChannelInboundHandler<ByteBuf> {

	private int count;
	
	@Override
	protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
		
		//把msg转成byte数组
		byte[] buffer = new byte[msg.readableBytes()];
		msg.readBytes(buffer);
		
		//将buffer转成字符串
		String message = new String(buffer, CharsetUtil.UTF_8);
		System.out.println("服务器接收到的数据:" + message);
		System.out.println("服务器接收到消息条数:" + (++this.count));
		
		//服务器回送数据给客户端,回送一个随机id值
		ByteBuf response = Unpooled.copiedBuffer(UUID.randomUUID().toString(), CharsetUtil.UTF_8);
		ctx.writeAndFlush(response);
	}
	
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		cause.printStackTrace();
		ctx.channel().close();
	}

}

3、客户端
NettyClient.java
 

package netty.tcpStickPackage;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

public class NettyClient {
	public static void main(String[] args) {
		EventLoopGroup group = new NioEventLoopGroup();
		
		try {
			Bootstrap bootstrap = new Bootstrap();
			bootstrap.group(group) //设置线程组
				.channel(NioSocketChannel.class)
				.handler(new LoggingHandler(LogLevel.DEBUG))
				.handler(new NettyClientInitializer()); //自定义一个初始化对象
			
			ChannelFuture cf = bootstrap.connect("127.0.0.1", 7000).sync();
			cf.channel().closeFuture().sync();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			group.shutdownGracefully();
		}
	}
}

NettyClientInitializer.java

package netty.tcpStickPackage;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;

public class NettyClientInitializer extends ChannelInitializer<SocketChannel> {

	@Override
	protected void initChannel(SocketChannel ch) throws Exception {
		ChannelPipeline pipeline = ch.pipeline();
		//加入一个自定义handler
		pipeline.addLast(new NettyClientHandler());
	}

}

NettyClientHandler.java

package netty.tcpStickPackage;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;

public class NettyClientHandler extends SimpleChannelInboundHandler<ByteBuf> {

	private int count;
	
	@Override
	protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
		//把msg转成byte数组
		byte[] buffer = new byte[msg.readableBytes()];
		msg.readBytes(buffer);
		String message = new String(buffer, CharsetUtil.UTF_8);
		
		System.out.println("客户端接收到的数据:" + message);
		System.out.println("客户端接收到消息条数:" + (++this.count));
	}

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		//使用客户端发送10条数据,hello server
		for (int i=0; i<10; i++) {
			ByteBuf buffer = Unpooled.copiedBuffer("hello,server", CharsetUtil.UTF_8);
			ctx.writeAndFlush(buffer);
		}
	}
	
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		cause.printStackTrace();
		ctx.channel().close();
	}
}

三、执行结果

1、服务端
开了3个客户端连接

2023-01-20 11:10:25.276 [] DEBUG [nioEventLoopGroup-2-1] io.netty.handler.logging.LoggingHandler :[id: 0xfd34bd30, L:/0:0:0:0:0:0:0:0:7000] READ: [id: 0x1b9cbe10, L:/127.0.0.1:7000 - R:/127.0.0.1:50527]
2023-01-20 11:10:25.278 [] DEBUG [nioEventLoopGroup-2-1] io.netty.handler.logging.LoggingHandler :[id: 0xfd34bd30, L:/0:0:0:0:0:0:0:0:7000] READ COMPLETE
2023-01-20 11:10:25.311 [] DEBUG [nioEventLoopGroup-3-1] io.netty.util.Recycler :-Dio.netty.recycler.maxCapacityPerThread: 4096
2023-01-20 11:10:25.311 [] DEBUG [nioEventLoopGroup-3-1] io.netty.util.Recycler :-Dio.netty.recycler.maxSharedCapacityFactor: 2
2023-01-20 11:10:25.311 [] DEBUG [nioEventLoopGroup-3-1] io.netty.util.Recycler :-Dio.netty.recycler.linkCapacity: 16
2023-01-20 11:10:25.311 [] DEBUG [nioEventLoopGroup-3-1] io.netty.util.Recycler :-Dio.netty.recycler.ratio: 8
2023-01-20 11:10:25.320 [] DEBUG [nioEventLoopGroup-3-1] io.netty.buffer.AbstractByteBuf :-Dio.netty.buffer.checkAccessible: true
2023-01-20 11:10:25.320 [] DEBUG [nioEventLoopGroup-3-1] io.netty.buffer.AbstractByteBuf :-Dio.netty.buffer.checkBounds: true
2023-01-20 11:10:25.322 [] DEBUG [nioEventLoopGroup-3-1] io.netty.util.ResourceLeakDetectorFactory :Loaded default ResourceLeakDetector: io.netty.util.ResourceLeakDetector@51d26066
服务器接收到的数据:hello,serverhello,serverhello,serverhello,serverhello,serverhello,serverhello,serverhello,serverhello,serverhello,server
服务器接收到消息条数:1
2023-01-20 11:10:54.361 [] DEBUG [nioEventLoopGroup-2-1] io.netty.handler.logging.LoggingHandler :[id: 0xfd34bd30, L:/0:0:0:0:0:0:0:0:7000] READ: [id: 0xcc7620a4, L:/127.0.0.1:7000 - R:/127.0.0.1:50564]
2023-01-20 11:10:54.362 [] DEBUG [nioEventLoopGroup-2-1] io.netty.handler.logging.LoggingHandler :[id: 0xfd34bd30, L:/0:0:0:0:0:0:0:0:7000] READ COMPLETE
服务器接收到的数据:hello,server
服务器接收到消息条数:1
服务器接收到的数据:hello,serverhello,server
服务器接收到消息条数:2
服务器接收到的数据:hello,serverhello,serverhello,server
服务器接收到消息条数:3
服务器接收到的数据:hello,serverhello,serverhello,server
服务器接收到消息条数:4
服务器接收到的数据:hello,server
服务器接收到消息条数:5
2023-01-20 11:11:23.570 [] DEBUG [nioEventLoopGroup-2-1] io.netty.handler.logging.LoggingHandler :[id: 0xfd34bd30, L:/0:0:0:0:0:0:0:0:7000] READ: [id: 0x77e7bcfe, L:/127.0.0.1:7000 - R:/127.0.0.1:50597]
2023-01-20 11:11:23.571 [] DEBUG [nioEventLoopGroup-2-1] io.netty.handler.logging.LoggingHandler :[id: 0xfd34bd30, L:/0:0:0:0:0:0:0:0:7000] READ COMPLETE
服务器接收到的数据:hello,server
服务器接收到消息条数:1
服务器接收到的数据:hello,server
服务器接收到消息条数:2
服务器接收到的数据:hello,serverhello,serverhello,serverhello,server
服务器接收到消息条数:3
服务器接收到的数据:hello,serverhello,serverhello,server
服务器接收到消息条数:4
服务器接收到的数据:hello,server
服务器接收到消息条数:5

2、客户端

客户端接收到的数据:0851c5de-99b6-4717-9603-763c0a53ba6c
客户端接收到消息条数:1

客户端接收到的数据:9f0533a8-fa6b-4002-864c-a4635a78bea8cc8b1396-24fb-4871-ba66-b82e9ffa7391086dfca2-04cf-4207-909d-06b246ec149d0f855148-0803-4cfc-8935-ada9479e7307ea3eac40-c0df-4f76-a5f3-0adc164c19d0
客户端接收到消息条数:1

客户端接收到的数据:036bcc0a-34ab-4add-b1cb-4b3c83c8148d7834d597-0a4e-4177-ad46-8ce796f05d952f92a65a-ba54-495a-a85e-0c043e9f37d176471a8f-1232-4867-8962-4faac90edf83cf120ed5-f850-4ab2-87ce-71342d31cecf
客户端接收到消息条数:1

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/173994.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

C++语法复习笔记-第6章 c++指针

文章目录1. 计算机内存1. 储存层次2. 内存单元与地址3. 指针定义2. 左值与右值1. 数组与指针1. 概念3. C中的原始指针1. 数组指针与指针数组2. const pointer 与 pointer to const3. 指向指针的指针4.关于野指针4.1 指向指针的指针4.2 NULL指针4.3 野指针5. 指针的基本运算5.1 …

MySQL 批量插入

文章目录MySQL批量插入10w条数据创建表创建函数创建存储过程调用存储过程MySQL批量插入10w条数据 创建表 创建emp&#xff08;部门&#xff09;表 创建dept&#xff08;员工&#xff09;表 创建函数 创建rand_num函数&#xff0c;随机生成部门编号&#xff0c;保证部门编…

Spark RDD算子

文章目录Spark RDD算子一、RDD 转换算子1、Value 类型(1) mapSpark RDD算子 RDD 方法也叫做RDD算子&#xff0c;主要分为两类&#xff0c;第一类是用来做转换的&#xff0c;例如flatMap()&#xff0c;Map()方法&#xff0c;第二类是行动的&#xff0c;例如&#xff1a;collenc…

Spring Security in Action 第八章 配置授权:api授权

本专栏将从基础开始&#xff0c;循序渐进&#xff0c;以实战为线索&#xff0c;逐步深入SpringSecurity相关知识相关知识&#xff0c;打造完整的SpringSecurity学习步骤&#xff0c;提升工程化编码能力和思维能力&#xff0c;写出高质量代码。希望大家都能够从中有所收获&#…

并查集(Java实现)

基本实现 任务&#xff1a; 维护多个不相交的集合&#xff0c;支持两种操作&#xff1a;合并两个集合&#xff0c;查询一个元素所在的集合。 说明&#xff1a; 维护一个森林&#xff0c;每一棵树都代表一个集合&#xff0c;树根元素为这个集合的代表元。利用数组father[]查询记…

[标准库]STM32F103R8T6 串口的收发

前言 这篇记录一下怎么调用标准库的函数来初始化一个串口&#xff0c;并调库实现发数据和收数据&#xff0c;以及串口收中断的使用。 越往深处学习越感觉其实32就是一个功能更加齐全和强大的MCU&#xff0c;其实跟51没有什么本质上的区别。很多设置的地方都是同质化的。比如需…

JVM知识点整理(整理中)

JVM知识点整理1、JVM与java体系结构1.1、java的体系结构1.2、JVM1.2.1、从跨平台的语言到跨语言的平台1.2.2、常用的JVM实现1.2.3、JVM的位置1.2.4、JDK、JER、JDK1.2.5、JVM的整体结构1.2.6、java代码的执行流程1.2.7、JVM的代码模型1.2.8、JVM的生命周期2、类加载子系统2.1、…

ARM NandFlash 介绍

一、NandFlash 的接口 1、Nand 的型号与命名 (1) Nand 的型号命名都有含义&#xff0c;就拿 K9F2G08 来示例分析一下&#xff1a;K9F 表示是三星公司的 NandFlash 系列。2G 表示 Nand 的大小是 2Gbit&#xff08;256MB&#xff09;。08 表示 Nand 是 8 位的&#xff08; 8 位…

员工入职管理系统|员工管理系统|基于SpringBoot+Vue的企业新员工入职系统

作者主页&#xff1a;编程指南针 作者简介&#xff1a;Java领域优质创作者、CSDN博客专家 、掘金特邀作者、多年架构师设计经验、腾讯课堂常驻讲师 主要内容&#xff1a;Java项目、毕业设计、简历模板、学习资料、面试题库、技术互助 收藏点赞不迷路 关注作者有好处 文末获取源…

SICTF2023 WP

前言 新年前的最后一场比赛&#xff0c;感谢shenghuo2师傅提供的misc和密码的wp&#xff0c;把misc和密码ak了&#xff0c;太强了 web 兔年大吉 源码 <?php highlight_file(__FILE__); error_reporting(0);class Happy{private $cmd;private $content;public function _…

Registration Center

CAP●一致性(Consistency)&#xff1a;所有节点在同一时间具有相同的数据&#xff1b;●可用性(Availability) &#xff1a;保证每个请求不管成功或者失败都有响应&#xff1b;某个系统的某个节点挂了&#xff0c;但是并不影响系统的接受或者发出请求。●分隔容忍(Partition to…

python循环语句

Python循环语句 文章目录Python循环语句一、实验目的二、实验原理三、实验环境四、实验内容五、实验步骤1.While循环结构2.While无限循环3.For循环语法4.break语句和continue语句一、实验目的 掌握循环结构的语法 二、实验原理 Python中的循环语句有 for 和 while。 Python…

AcWing蓝桥杯AB组辅导课07、贪心

文章目录前言一、贪心模板题例题1&#xff1a;AcWing 104. 货仓选址&#xff08;贪心&#xff0c;简单&#xff0c;算法竞赛进阶指南&#xff09;分析题解&#xff1a;贪心思路例题例题1&#xff1a;AcWing 1055. 股票买卖 II&#xff08;贪心、状态机&#xff0c;简单&#xf…

[ESP][驱动]GT911 ESP系列驱动

GT911ForESP GT911在ESP系列上的驱动&#xff0c;基于IDF5.0&#xff0c;ESP32S3编写 本库使用面向对象思想编写&#xff0c;可创建多设备多实例 Github&#xff0c;Gitee同步更新&#xff0c;Gitee仅作为下载仓库&#xff0c;提交Issue和Pull request请到Github Github: h…

具体芯片的I2C_Adapter驱动分析

具体芯片的I2C_Adapter驱动分析 文章目录具体芯片的I2C_Adapter驱动分析参考资料&#xff1a;一、 I2C控制器内部结构1.1 通用的简化结构1.2 IMX6ULL的I2C控制器内部结构二、 I2C控制器操作方法三、 分析代码3.1 设备树3.2 驱动程序分析致谢参考资料&#xff1a; Linux内核真正…

03_筛选标记2.0版和3.0版FIND及ColorIndex

文章目录2.0版工作簿筛选标记筛选sheet标记取消筛选标记3.0版ColorIndex 下标代码特别鸣谢,大佬的分享FIND方法的使用2.0版 工作簿筛选标记 Option Explicit Sub 自动筛选()Dim Town As StringDim wsh As WorksheetCall 初始化 初始化表格状态Town InputBox("请输入街…

SLAM笔记——turtlebot传感器ekf实验实验

这里写目录标题实验内容实验准备msg数据类型给uwb和odom增加噪声robot_pose_ekf发布路径实验结果实验内容 本实验将在gazebo仿真环境中使用ekf进行传感器数据融合。本文使用turtlebot3进行实验&#xff0c;turtlebot本身会发布odom和imu。imu的误差可以在urdf文件中进行调整&a…

追梦之旅【数据结构篇】——对数据结构的认知 + 初识时间复杂度和空间复杂度~

详解C语言函数模块知识(下篇&#xff09;&#x1f60e;前言&#x1f64c;浅谈数据结构~&#x1f64c;1、什么是数据结构&#xff1f;(ˇˍˇ) 想&#xff5e;2、什么是算法&#xff1f;ˇˍˇ) 想&#xff5e;3、数据结构和算法的重要性&#x1f60a;4、如何才能学好数据结构呢…

初识 NodeJS(基于 Chrome V8 引擎的 JavaScript 运行时环境)

初识 NodeJS&#xff08;基于 Chrome V8 引擎的 JavaScript 运行时环境&#xff09;参考描述NodeJSNodeJS 可以做什么&#xff1f;特点用武之地获取检测运行JavaScript 运行时环境JavsScript 引擎浏览器中的 JavaScript 运行时环境Chrome 浏览器运行时环境NodeJS 中的 JavaScri…

【着色器实现海面效果_菲尼尔/Unlit/Transparent】

1.水体颜色 2.反射,水面波纹流动 3.折射、水底、水底透明度和折射 4.焦散,在水底接近岸边的水域 5.岸边泡沫,水花接近岸边的泡沫 6.水体运动,顶点动画 用灯光模式是Light Model :Unilt Render Type:Transparent 获取水面深度 利用这个节点,从深度图获取世界空间的位…