Netty解决TCP粘包拆包问题

Netty解决TCP粘包/拆包导致的半包读写问题 一.TCP粘包/拆包问题说明   TCP是个“流”协议,就是没有界限的一串数据。TCP底层并不了解上层业务数据的具体含义,它会根据TCP缓冲区的实际情况进行包拆分,所以在业务上认为,一个完整的包可能会被TCP拆分成多个包进行发送,也有可能把多个小的包封装成一个大的数据包发送,这就是所谓的TCP粘包和拆包问题。 二.利用LinedBasedFrameDecoder解决TCP粘包问题    为了 阅读详情

什么是TCP粘包/拆包

TCP是一种面向连接的、可靠的、基于字节流的传输层通信协议。TCP是基于字节流传输的,就像河流一样,数据“流”式传输,数据中间没有分界。

TCP底层并不了解上层业务数据的具体含义,它会根据TCP缓冲区的实际情况进行包的划分,所以一个完整的数据包可能会拆分成多个包传输,或者多个数据包可能会合并成一个包传输,这就是所谓的TCP的粘包/拆包问题。如下图所示:

在这里插入图片描述

正常业务逻辑上,Client需要向Server发送D1和D2两个数据包(如上图第一种情况);但实际在TCP传输的过程中,可能会将D1和D2合并为一个数据包发送(如上图第二种情况);也有可能D2被拆分成两个数据包,其中一个跟D1合并成了一个数据包(如上图第三种情况);又或者D1被拆分成两个数据包,其中一个跟D2合并成了一个数据包(如上图第四种情况)。

还有一种可能,当服务端接收滑窗非常小,而D1、D2数据又很大的时候,可能会分多次才能将D1、D2两个数据接收完全。

TCP粘包/拆包发送的原因

TCP发送粘包/拆包的原因主要有以下几个:
(1)应用程序write写入的字节大小大于套接口发送缓冲区大小。
(2)进行MSS(最大报文段长度)大小的TCP分段。当TCP报文段的长度大于MSS时,要进行分段传输。
(3)以太网帧的payload大于MTU(最大传输单元)进行IP分片。一个IP数据报在以太网中 传输,如果它的长度大于该MTU值,就要进行分片传输,使得每片数据报的长度小于MTU。

使用Netty未考虑TCP粘包的示例

仍然还是用之前的客户端向服务端请求时间的案例来改造。之前的示例没有出现粘包/拆包问题是因为客户端与服务器之间只是一问一答,并没有太大的流量压力。这次为了呈现问题,我们将服务器端增加一个计数,每收到一个TCP数据包计数加一;在客户端上,循环发送100条请求,每接收到一条服务端的回复也计数加一。

服务端NettyServerTest类:

package com.test.netty;

import io.netty.bootstrap.ServerBootstrap;
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;

public class NettyServerTest {
	
	public void bind(int port) throws InterruptedException {
		// NioEventLoopGroup 是用来处理I/O操作的多线程事件循环器
		// 第一个经常被叫做‘boss’,用来接收进来的连接
		EventLoopGroup bossGroup = new NioEventLoopGroup();
		// 第二个经常被叫做‘worker’,用来处理已经被接收的连接,一旦‘boss’接收到连接,就会把连接信息注册到‘worker’上
		EventLoopGroup workerGroup = new NioEventLoopGroup();
		try {
			// ServerBootstrap 是一个启动 NIO 服务的辅助启动类
			ServerBootstrap b = new ServerBootstrap();
			b.group(bossGroup, workerGroup)
				.channel(NioServerSocketChannel.class)
				// 设置 socket 的参数选项
				.option(ChannelOption.SO_BACKLOG, 1024)
				.childHandler(new childChannelHandler());
			// 绑定端口,同步等待成功
			ChannelFuture f = b.bind(port).sync();
			
			// 等待服务端监听端口关闭
			f.channel().closeFuture().sync();
			
		}finally {
			// 优雅退出,释放线程资源
			bossGroup.shutdownGracefully();
			workerGroup.shutdownGracefully();
		}
	}
	
	/**
	 * ChannelInitializer 是一个特殊的处理类,他的目的是帮助使用者配置一个新的 Channel
	 * @author 
	 *
	 */
	private class childChannelHandler extends ChannelInitializer<SocketChannel>{

		@Override
		protected void initChannel(SocketChannel arg0) throws Exception {
			arg0.pipeline().addLast(new ServerTestHandler());
		}
		
	}

	public static void main(String[] args) throws InterruptedException {
		int port = 8888;
		new NettyServerTest().bind(port);
	}

}

服务端ServerTestHandler类:

package com.test.netty;

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

public class ServerTestHandler extends ChannelInboundHandlerAdapter  {
	
	private int counter;
	
	/**
	 * 每当从客户端收到新的数据时,channelRead()方法会在收到消息时被调用
	 */
	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		ByteBuf buf = (ByteBuf) msg;
		byte[] req = new byte[buf.readableBytes()];
		buf.readBytes(req);
		String body = new String(req, "UTF-8").substring(0, req.length - System.getProperty("line.separator").length());
		System.out.println("The time server receive order : " + body + " ; the counter is : " + ++counter);
		String currentTime = "QUERY TIME ORDER".equalsIgnoreCase(body) ? new java.util.Date(
				System.currentTimeMillis()).toString() : "BAD ORDER";
			currentTime = currentTime + System.getProperty("line.separator");
		ByteBuf resp = Unpooled.copiedBuffer(currentTime.getBytes());
		ctx.write(resp);
	}
	
	@Override
	public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
		// 将消息发送发送队列中的消息写入到SocketChannel中发送给对方
		ctx.flush();
	}
	
	/**
	 * exceptionCaught() 事件处理方法是当出现 Throwable 对象才会被调用,
	 * 即当 Netty 由于 IO 错误或者处理器在处理事件时抛出的异常时
	 */
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
		System.out.println(cause.getMessage());
		ctx.close();
	}
}

客户端NettyClientTest:

package com.test.netty;

import io.netty.bootstrap.Bootstrap;
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;

public class NettyClientTest {

	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 {
					// TODO Auto-generated method stub
					ch.pipeline().addLast(new ClientTestHandler());
				}
				
			});
			// 发起异步连接操作
			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 = 8888;
		new NettyClientTest().connect(port, "127.0.0.1");
	}

}

客户端ClientTestHandler类:

package com.test.netty;

import java.util.logging.Logger;

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

public class ClientTestHandler extends ChannelInboundHandlerAdapter{
	
	private static final Logger logger = Logger.getLogger(ClientTestHandler.class.getName());
	private int counter;
	private byte[] req;
	
	public ClientTestHandler() {
		req = ("QUERY TIME ORDER" + System.getProperty("line.separator")).getBytes();
	}
	
	@Override
	public void channelActive(ChannelHandlerContext ctx) {
		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 {
		ByteBuf buf = (ByteBuf)msg;
		byte[] req = new byte[buf.readableBytes()];
		buf.readBytes(req);
		String body = new String(req, "UTF-8");
		System.out.println("Now is : " + body + " ; the counter is : " + ++counter);
	}
	
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
		// 释放资源
		logger.warning("Unexpected exception from downstream : " + cause.getMessage());
		ctx.close();
	}
}

执行结果:

在这里插入图片描述

服务端的运行结果表明它只接收到了两条消息,第一条中包含57条“QUERY TIME ORDER”,第二条中包含43条“QUERY TIME ORDER”,这说明发生了TCP粘包。

而客户端也本应该收到两条消息,但实际上只接收到了一条包含两条“QUERY TIME ORDER”的消息,说明客户端也发生了粘包。

解决TCP粘包/拆包

利用LineBasedFrameDecoder解决TCP粘包问题

Netty官方提供的LineBasedFrameDecoder和StringDecoder搭配使用可以解决TCP粘包问题。LineBasedFrameDecoder的工作原理是它依次遍历ByteBuf中的可读字节,判断看是否有“\n”或者“\r\n”,如果有,就以此位置为结束位置,从可读索引到结束位置区间的字节就组成了一行。它是以换行符为结束标志的解码器,支持携带结束符或者不携带结束符两种解码方式,同时支持配置单行的最大长度。如果连续读取到最大长度后仍然没有发现换行符,就会抛出异常,同时忽略掉之前读到的异常码流。

StringDecoder的功能非常简单,就是将接收到的对象转换成字符串,然后继续调用后面的handler。使用了StringDecoder后就不需要在自定义的handler中来做ByteBuf与String的转换了。LineBasedFrameDecoder+StringDecoder组合就是按行切换的文本解码器,它被设计用来支持TCP的粘包和拆包。

我们继续使用上面的时间服务器的例子来展示LineBasedFrameDecoder和StringDecoder搭配使用来解决TCP粘包问题。

服务端NettyServerTest类:

package com.test.netty;

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

public class NettyServerTest {
	
	public void bind(int port) throws InterruptedException {
		// NioEventLoopGroup 是用来处理I/O操作的多线程事件循环器
		// 第一个经常被叫做‘boss’,用来接收进来的连接
		EventLoopGroup bossGroup = new NioEventLoopGroup();
		// 第二个经常被叫做‘worker’,用来处理已经被接收的连接,一旦‘boss’接收到连接,就会把连接信息注册到‘worker’上
		EventLoopGroup workerGroup = new NioEventLoopGroup();
		try {
			// ServerBootstrap 是一个启动 NIO 服务的辅助启动类
			ServerBootstrap b = new ServerBootstrap();
			b.group(bossGroup, workerGroup)
				.channel(NioServerSocketChannel.class)
				// 设置 socket 的参数选项
				.option(ChannelOption.SO_BACKLOG, 1024)
				.childHandler(new childChannelHandler());
			// 绑定端口,同步等待成功
			ChannelFuture f = b.bind(port).sync();
			
			// 等待服务端监听端口关闭
			f.channel().closeFuture().sync();
			
		}finally {
			// 优雅退出,释放线程资源
			bossGroup.shutdownGracefully();
			workerGroup.shutdownGracefully();
		}
	}
	
	/**
	 * ChannelInitializer 是一个特殊的处理类,他的目的是帮助使用者配置一个新的 Channel
	 * @author 
	 *
	 */
	private class childChannelHandler extends ChannelInitializer<SocketChannel>{

		@Override
		protected void initChannel(SocketChannel arg0) throws Exception {
			arg0.pipeline().addLast(new LineBasedFrameDecoder(1024));
			arg0.pipeline().addLast(new StringDecoder());
			arg0.pipeline().addLast(new ServerTestHandler());
		}
		
	}

	public static void main(String[] args) throws InterruptedException {
		int port = 8888;
		new NettyServerTest().bind(port);
	}

}

在initChannel(SocketChannel arg0)方法体中,在ServerTestHandler之前增加了LineBasedFrameDecoder和StringDecoder。其中给LineBasedFrameDecoder配置了最大单行长度为1024。

服务端ServerTestHandler类:

package com.test.netty;

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

public class ServerTestHandler extends ChannelInboundHandlerAdapter  {
	
	private int counter;
	
	/**
	 * 每当从客户端收到新的数据时,channelRead()方法会在收到消息时被调用
	 */
	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		String body = (String) msg;
//		byte[] req = new byte[buf.readableBytes()];
//		buf.readBytes(req);
//		String body = new String(req, "UTF-8").substring(0, req.length - System.getProperty("line.separator").length());
		System.out.println("The time server receive order : " + body + " ; the counter is : " + ++counter);
		String currentTime = "QUERY TIME ORDER".equalsIgnoreCase(body) ? new java.util.Date(
				System.currentTimeMillis()).toString() : "BAD ORDER";
			currentTime = currentTime + System.getProperty("line.separator");
		ByteBuf resp = Unpooled.copiedBuffer(currentTime.getBytes());
		ctx.write(resp);
	}
	
	@Override
	public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
		// 将消息发送发送队列中的消息写入到SocketChannel中发送给对方
		ctx.flush();
	}
	
	/**
	 * exceptionCaught() 事件处理方法是当出现 Throwable 对象才会被调用,
	 * 即当 Netty 由于 IO 错误或者处理器在处理事件时抛出的异常时
	 */
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
		System.out.println(cause.getMessage());
		ctx.close();
	}
}

客户端NettyClientTest类:

package com.test.netty;

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

public class NettyClientTest {

	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 {
					ch.pipeline().addLast(new LineBasedFrameDecoder(1024));
					ch.pipeline().addLast(new StringDecoder());
					ch.pipeline().addLast(new ClientTestHandler());
				}
				
			});
			// 发起异步连接操作
			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 = 8888;
		new NettyClientTest().connect(port, "127.0.0.1");
	}

}

客户端ClientTestHandler类:

package com.test.netty;

import java.util.logging.Logger;

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

public class ClientTestHandler extends ChannelInboundHandlerAdapter{
	
	private static final Logger logger = Logger.getLogger(ClientTestHandler.class.getName());
	private int counter;
	private byte[] req;
	
	public ClientTestHandler() {
		req = ("QUERY TIME ORDER" + System.getProperty("line.separator")).getBytes();
	}
	
	@Override
	public void channelActive(ChannelHandlerContext ctx) {
		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;
//		byte[] req = new byte[buf.readableBytes()];
//		buf.readBytes(req);
//		String body = new String(req, "UTF-8");
		System.out.println("Now is : " + body + " ; the counter is : " + ++counter);
	}
	
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
		// 释放资源
		logger.warning("Unexpected exception from downstream : " + cause.getMessage());
		ctx.close();
	}
}

运行结果:

在这里插入图片描述

可以看到服务端都正确地接收到了100条客户端请求,并且客户端也正确地接收到了100条服务端响应。

DelimiterBasedFrameDecoder解决TCP粘包

LineBasedFrameDecoder是以回车换行符作为消息结束符的,我们可以使用DelimiterBasedFrameDecoder自定义特殊分隔符作为消息的结束符。我们再对前面的程序做点修改,将其使用DelimiterBasedFrameDecoder将“$_”作为特殊分隔符。

服务端NettyServerTest类:

package com.test.netty;

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;

public class NettyServerTest {
	
	public void bind(int port) throws InterruptedException {
		// NioEventLoopGroup 是用来处理I/O操作的多线程事件循环器
		// 第一个经常被叫做‘boss’,用来接收进来的连接
		EventLoopGroup bossGroup = new NioEventLoopGroup();
		// 第二个经常被叫做‘worker’,用来处理已经被接收的连接,一旦‘boss’接收到连接,就会把连接信息注册到‘worker’上
		EventLoopGroup workerGroup = new NioEventLoopGroup();
		try {
			// ServerBootstrap 是一个启动 NIO 服务的辅助启动类
			ServerBootstrap b = new ServerBootstrap();
			b.group(bossGroup, workerGroup)
				.channel(NioServerSocketChannel.class)
				// 设置 socket 的参数选项
				.option(ChannelOption.SO_BACKLOG, 1024)
				.childHandler(new childChannelHandler());
			// 绑定端口,同步等待成功
			ChannelFuture f = b.bind(port).sync();
			
			// 等待服务端监听端口关闭
			f.channel().closeFuture().sync();
			
		}finally {
			// 优雅退出,释放线程资源
			bossGroup.shutdownGracefully();
			workerGroup.shutdownGracefully();
		}
	}
	
	/**
	 * ChannelInitializer 是一个特殊的处理类,他的目的是帮助使用者配置一个新的 Channel
	 * @author 
	 *
	 */
	private class childChannelHandler extends ChannelInitializer<SocketChannel>{

		@Override
		protected void initChannel(SocketChannel arg0) throws Exception {
			ByteBuf delimiter = Unpooled.copiedBuffer("$_".getBytes());
			arg0.pipeline().addLast(new DelimiterBasedFrameDecoder(1024, delimiter));
			arg0.pipeline().addLast(new StringDecoder());
			arg0.pipeline().addLast(new ServerTestHandler());
		}
		
	}

	public static void main(String[] args) throws InterruptedException {
		int port = 8888;
		new NettyServerTest().bind(port);
	}

}

服务端ServerTestHandler类:

package com.test.netty;

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

public class ServerTestHandler extends ChannelInboundHandlerAdapter  {
	
	private int counter;
	
	/**
	 * 每当从客户端收到新的数据时,channelRead()方法会在收到消息时被调用
	 */
	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		String body = (String) msg;
//		byte[] req = new byte[buf.readableBytes()];
//		buf.readBytes(req);
//		String body = new String(req, "UTF-8").substring(0, req.length - System.getProperty("line.separator").length());
		System.out.println("The time server receive order : " + body + " ; the counter is : " + ++counter);
		String currentTime = "QUERY TIME ORDER".equalsIgnoreCase(body) ? new java.util.Date(
				System.currentTimeMillis()).toString() : "BAD ORDER";
			currentTime = currentTime + "$_";
		ByteBuf resp = Unpooled.copiedBuffer(currentTime.getBytes());
		ctx.write(resp);
	}
	
	@Override
	public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
		// 将消息发送发送队列中的消息写入到SocketChannel中发送给对方
		ctx.flush();
	}
	
	/**
	 * exceptionCaught() 事件处理方法是当出现 Throwable 对象才会被调用,
	 * 即当 Netty 由于 IO 错误或者处理器在处理事件时抛出的异常时
	 */
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
		System.out.println(cause.getMessage());
		ctx.close();
	}
}

客户端NettyClientTest类:

package com.test.netty;

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;

public class NettyClientTest {

	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());
					ch.pipeline().addLast(new DelimiterBasedFrameDecoder(1024, delimiter));
					ch.pipeline().addLast(new StringDecoder());
					ch.pipeline().addLast(new ClientTestHandler());
				}
				
			});
			// 发起异步连接操作
			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 = 8888;
		new NettyClientTest().connect(port, "127.0.0.1");
	}

}

客户端ClientTestHandler类:

package com.test.netty;

import java.util.logging.Logger;

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

public class ClientTestHandler extends ChannelInboundHandlerAdapter{
	
	private static final Logger logger = Logger.getLogger(ClientTestHandler.class.getName());
	private int counter;
	private byte[] req;
	
	public ClientTestHandler() {
		req = ("QUERY TIME ORDER" + "$_").getBytes();
	}
	
	@Override
	public void channelActive(ChannelHandlerContext ctx) {
		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;
//		byte[] req = new byte[buf.readableBytes()];
//		buf.readBytes(req);
//		String body = new String(req, "UTF-8");
		System.out.println("Now is : " + body + " ; the counter is : " + ++counter);
	}
	
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
		// 释放资源
		logger.warning("Unexpected exception from downstream : " + cause.getMessage());
		ctx.close();
	}
}

执行结果:

在这里插入图片描述

从执行结果看,没有发送TCP粘包的情况。

FixedLengthFrameDecoder解决TCP粘包

FixedLengthFrameDecoder是固定长度解码器,我们可以设置消息的长度。我们再用FixedLengthFrameDecoder修改一下上面的例子。

服务端NettyServerTest类:

package com.test.netty;

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

public class NettyServerTest {
	
	public void bind(int port) throws InterruptedException {
		// NioEventLoopGroup 是用来处理I/O操作的多线程事件循环器
		// 第一个经常被叫做‘boss’,用来接收进来的连接
		EventLoopGroup bossGroup = new NioEventLoopGroup();
		// 第二个经常被叫做‘worker’,用来处理已经被接收的连接,一旦‘boss’接收到连接,就会把连接信息注册到‘worker’上
		EventLoopGroup workerGroup = new NioEventLoopGroup();
		try {
			// ServerBootstrap 是一个启动 NIO 服务的辅助启动类
			ServerBootstrap b = new ServerBootstrap();
			b.group(bossGroup, workerGroup)
				.channel(NioServerSocketChannel.class)
				// 设置 socket 的参数选项
				.option(ChannelOption.SO_BACKLOG, 1024)
				.childHandler(new childChannelHandler());
			// 绑定端口,同步等待成功
			ChannelFuture f = b.bind(port).sync();
			
			// 等待服务端监听端口关闭
			f.channel().closeFuture().sync();
			
		}finally {
			// 优雅退出,释放线程资源
			bossGroup.shutdownGracefully();
			workerGroup.shutdownGracefully();
		}
	}
	
	/**
	 * ChannelInitializer 是一个特殊的处理类,他的目的是帮助使用者配置一个新的 Channel
	 * @author 
	 *
	 */
	private class childChannelHandler extends ChannelInitializer<SocketChannel>{

		@Override
		protected void initChannel(SocketChannel arg0) throws Exception {
			//ByteBuf delimiter = Unpooled.copiedBuffer("$_".getBytes());
			//arg0.pipeline().addLast(new DelimiterBasedFrameDecoder(1024, delimiter));
			arg0.pipeline().addLast(new FixedLengthFrameDecoder(10));
			arg0.pipeline().addLast(new StringDecoder());
			arg0.pipeline().addLast(new ServerTestHandler());
		}
		
	}

	public static void main(String[] args) throws InterruptedException {
		int port = 8888;
		new NettyServerTest().bind(port);
	}

}

服务端ServerTestHandler类:

package com.test.netty;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

public class ServerTestHandler extends ChannelInboundHandlerAdapter  {
	
	private int counter;
	
	/**
	 * 每当从客户端收到新的数据时,channelRead()方法会在收到消息时被调用
	 */
	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		String body = (String) msg;
//		byte[] req = new byte[buf.readableBytes()];
//		buf.readBytes(req);
//		String body = new String(req, "UTF-8").substring(0, req.length - System.getProperty("line.separator").length());
		System.out.println("The time server receive order : " + body + " ; the counter is : " + ++counter);
		//String currentTime = "QUERY TIME ORDER".equalsIgnoreCase(body) ? new java.util.Date(
		//		System.currentTimeMillis()).toString() : "BAD ORDER";
		//	currentTime = currentTime + "$_";
		//ByteBuf resp = Unpooled.copiedBuffer(currentTime.getBytes());
		//ctx.write(resp);
	}
	
	@Override
	public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
		// 将消息发送发送队列中的消息写入到SocketChannel中发送给对方
		ctx.flush();
	}
	
	/**
	 * exceptionCaught() 事件处理方法是当出现 Throwable 对象才会被调用,
	 * 即当 Netty 由于 IO 错误或者处理器在处理事件时抛出的异常时
	 */
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
		System.out.println(cause.getMessage());
		ctx.close();
	}
}

客户端NettyClientTest类:

package com.test.netty;

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

public class NettyClientTest {

	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());
					//ch.pipeline().addLast(new DelimiterBasedFrameDecoder(1024, delimiter));
					ch.pipeline().addLast(new FixedLengthFrameDecoder(10));
					ch.pipeline().addLast(new StringDecoder());
					ch.pipeline().addLast(new ClientTestHandler());
				}
				
			});
			// 发起异步连接操作
			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 = 8888;
		new NettyClientTest().connect(port, "127.0.0.1");
	}

}

客户端ClientTestHandler类:

package com.test.netty;

import java.util.logging.Logger;

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

public class ClientTestHandler extends ChannelInboundHandlerAdapter{
	
	private static final Logger logger = Logger.getLogger(ClientTestHandler.class.getName());
	private int counter;
	private byte[] req;
	
	public ClientTestHandler() {
		req = ("QUERY TIME ORDER").getBytes();
	}
	
	@Override
	public void channelActive(ChannelHandlerContext ctx) {
		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;
//		byte[] req = new byte[buf.readableBytes()];
//		buf.readBytes(req);
//		String body = new String(req, "UTF-8");
		System.out.println("Now is : " + body + " ; the counter is : " + ++counter);
	}
	
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
		// 释放资源
		logger.warning("Unexpected exception from downstream : " + cause.getMessage());
		ctx.close();
	}
}

执行结果:

在这里插入图片描述

从执行结果可以看到,服务端接收到的消息都是分成了10 byte一包的。

netty学习二(解决tcp/udp 粘包,拆包问题) 在通讯协议中,粘包,拆包是常发生的事情,而netty则很好的给出了三种解决方式,下面分别介绍: 一;利用LineBasedFrameDecoder解决TCP粘包问题 直接上代码, Client类: package stickorApartPackageResolveOne.one; import io.netty.bootstrap.Bootstrap; import io.nett... 阅读详情

相关推荐

Netty接收报文长度问题

对于netty的接收数据字节长度,之前资料上是写着最大1024字节,但是否有设置参数可以支持单条报文接收大于1024字节,还不清楚; 查了下可以设置: option(ChannelOption.SO_RCVBUF,1024*16).//设置接收缓冲区 option(ChannelOption.SO_SNDBUF,1024*16);//设置发送缓冲区 但实际上运行时出现: 14:19:3...

jiezhang656的专栏 9419

Netty接收超过1024字节

Netty缓冲区 Netty接收超过1024字节 Netty默认接收字节大小 Netty一次接收超过1024的数据

qq_36665310的博客 9388

游戏资源解包神器NSCB实战:手把手教你提取Switch游戏视频(nsm转MP4)

本文详细介绍了如何使用NSCB工具链从Switch游戏中提取nsm视频和hca音频资源,并将其转换为可编辑的MP4和MP3格式。通过NSC Builder、CriPakTools等工具的分步操作指南,帮助内容创作者高效获取游戏资源,同时提供音视频同步合成、批量处理等高级技巧,为创意素材制作提供完整解决方案。

weixin_29197835的博客 922

Netty的Channel.write写数据不能超过1024byte的问题解决

开发的时候总会遇到一些有趣的问题,Netty发送不了1024byte!已解决! 问题描述 这次主要使用netty建立WebSocket服务端,服务端可以正常收到消息,服务端调用writeAndFlush 客户端无法收到消息 调试 将io.netty日志等级降低到debug 日志打印 Encoding WebSocket Frame opCode=1 length=1074 length超过1024客户端就无法收到消息 服务端收到:{"random":"5926","code":1,"roomId":1} 2

maction的博客 2241

告别乱码!手把手教你用docx4j实现Word转PDF(附完整中文字体配置)

本文详细介绍了如何使用纯Java库docx4j实现Word到PDF的精准转换,并重点解决了中文乱码这一核心痛点。文章提供了从环境搭建、核心代码实现到中文字体配置的完整教程,特别针对Linux服务器部署场景,给出了详细的字体安装与映射方案,确保跨平台转换的稳定性和准确性。

nokia的博客 1162

linux系统中实现智能家居的基本方法

使用QT开发智能家居中的一个物联应用,通过云服务器远程控制设备与设备进行通信。在生活中,可以使用WIFI智能插座控制电器开关,比如远程开启热水器,远程打开空调,窗帘等等。包括:WIFI联网,注册到云服务器上,编写QT UI通过网络来与云服务器通信,然后再下发指令到这个连网的设备。硬件说明:需要有一个串口转WIFI模块,另外需要加上一个USB-TTL模块,外加一根T口USB连接线,可接入PC电脑调试。

嵌入式技术开发 2613

netty接收大文件的方法

参考:http://blog.csdn.net/linuu/article/details/51371595 https://www.jianshu.com/p/a0a51fd79f62 netty默认是只能接收1024个字节,但是我们要传输大文件怎么办? 上代码: 改之后服务端: package server; import io.netty.bootstrap.ServerBo...

weixin_30653023的博客 985

使用 Simulink 和 Simscape Electrical 工具箱设计一个 Buck 转换器系统

Buck 转换器(降压转换器)是一种常用的 DC-DC 转换器,用于将较高的输入电压转换为较低的输出电压。为了评估其抗干扰能力,我们可以在模型中引入不同的干扰源,并观察系统的响应情况。电网电压波动:输入电压的变化。负载突变:负载电阻或电感的变化。电磁干扰:高频噪声或脉冲干扰。通过模拟这些干扰,我们可以分析系统的动态响应特性,并采取相应的措施来提高系统的抗干扰能力。

xiaoheshang_123的博客 384

Netty如何优雅地解决TCP粘包、拆包问题

TCP粘包是指,发送方发送的多个数据包被接收方合并成一个数据包接收。这种情况通常发生在发送方的多个write操作被合并到同一个TCP段中,或者接收方的接收缓冲区被填满,导致多个数据包被合并。例如,假设发送方发送了两个数据包,分别是“Hello”和“World”,接收方可能会接收到一个数据包“HelloWorld”。这会导致接收方无法正确区分这两个数据包,从而引发逻辑错误。TCP粘包和拆包问题是开发人员在处理TCP通信时必须面对的挑战。

一位努力搬砖程序员。在这里,我会分享关于编程技巧、项目实战经验以及对新技术的见解。希望通过我的文章能够帮助你在技术路上更进一步。期待与你共同学习和成长! 1247

【Envi风暴】Envi5.6安装图文教程(附Envi5.6完整版下载)

【Envi风暴】Envi5.6与应用商店app store安装图文教程(附Envi5.6完整版下载)从文末网盘下载完整的ENVI5.6安装包,如下所示:双击envi56-win.exe,开始安装。将f__x64下的两个补丁文件拷贝到安装路径。将f__x86下的两个补丁文件拷贝到安装路径。

智慧空间实验室 9276

【OpenClaw从入门到精通】第07篇:2026实测!零基础开发OpenClaw自定义Skill——招聘外呼自动邀约完整教程

本文聚焦OpenClaw自定义Skill开发全流程,针对现成技能无法满足个性化场景(如专属招聘流程、内部系统对接)的痛点,以“招聘外呼自动邀约”为实战案例,从概念认知、环境搭建、分步开发到测试优化,手把手教读者从零构建自定义Skill。内容涵盖Skill目录结构、SKILL.md核心配置、Python主逻辑实现、API对接、安全配置等关键环节,融入2026年ClawHavoc事件安全警示,强调最小权限、凭证安全等开发原则。所有代码经实测可运行,步骤详尽且兼顾新手友好与进阶需求。

专注于人工智能、软件开发、工控自动化、工厂数字化及智能化等领域,希望和大家共同进步! 1199

Netty如何解决TCP中的粘包和拆包问题

粘包和拆包是TCP网络编程中不可避免的,无论是服务端还是客户端,当我们读取或者发送消息的时候,都需要考虑TCP底层的粘包/拆包机制。TCP是个“流”协议,所谓流,就是没有界限的一串数据。TCP底层并不了解上层业务数据的具体含义,它会根据TCP缓冲区的实际情况进行包的划分,所以在业务上认为,一个完整的包可能会被TCP拆分成多个包进行发送,也有可能把多个小的包封装成一个大的数据包发送,这就是所谓的TCP粘包和拆包问题。...

lengyingzhang的博客 3599

CKA-题库-简洁参考答案-反复练习20遍-必过!!!

新版CKA考试已于2020年9月1日正式上线! 考试模式:线上考试 考试时间:2小时 认证有效期:3年 软件版本:Kubernetes v1.19 重考政策:可接受1次重考 经验水平:中級 题目数量:17题 题库量小:随机的题目重复率极高 考试时可打开两个浏览器Tab,一个是考试窗口,一个用来查阅官方文档](https://kubernetes.io/docs/) 01 Task - 英文 Create a new ClusterRole named deployment-clusterrole tha.

随笔记录-分享&记忆 7334

netty之TCP粘包拆包问题解决

TCP粘包拆包问题解决 什么TCP粘包和拆包问题 假设客户端向服务端连续发送了两个数据包,分别用ABC和DEF来表示,那么服务端收到的数据可以分为以下三种情况: 第一种情况,接收端正常收到两个数据包,即没有发生拆包和粘包的现象。 第二种情况,接收端只收到一个数据包,这一个数据包中包含了发送端发送的两个数据包的信息,这种现象即为粘包。 第三种情况,接收端收到了两个数据包,但是这两个数据包要么是不完整的,要么就是多出来一块,这种情况即发生了拆包和粘包。 为什么会发生TCP粘包和拆包 发生TCP粘包的原因:

morris 1万+

UNet 改进(19):与ASPP结合的图像分割模型

这个代码实现了一个改进版的UNet模型,在传统的UNet架构基础上,引入了ASPP模块来增强模型捕获多尺度上下文信息的能力。​​UNet主干网络​​:经典的编码器-解码器结构,带有跳跃连接​​ASPP模块​​:位于瓶颈层,用于提取多尺度特征。

2401_82355416的博客 884

精雕软件(JDpaint) 5.5 绿色版

精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版

Netty是如何解决TCP的粘包和拆包问题的?

TCP是个“流协议”,所谓流,就是没有界限的一连串数据,没有界限。TCP底层不了解业务数据的含义,它会根据TCP缓冲区的实际情况进行包的划分,所以业务上认为,一个完整的包可能被TCP拆分为多个包进行发送,也可能把多个小包封装成一个大的数据包进行发送,这就是所谓的TCP粘包和拆包问题。

LMR的博客 1万+

Devexpress16.2.6破解工具

Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具

Netty解决TCP粘包/拆包的问题

什么是TCP粘包/拆包   首先要明确, 粘包问题中的 “包”, 是指应用层的数据包.在TCP的协议头中, 没有如同UDP一样的 “报文长度” 字段,但是有一个序号字段.   站在传输层的角度, TCP是一个一个报文传过来的. 按照序号排好序放在缓冲区中.   站在应用层的角度, 看到的只是一串连续的字节数据.那么应用程序看到了这一连串的字节数据, 就不知道从哪个部分开始到哪个部分是一个完整的应用...

波波烤鸭的博客 3755

lwip-2.0.3

lwip是瑞典计算机科学院(SICS)的Adam Dunkels 开发的一个小型开源的TCP/IP协议栈。实现的重点是在保持TCP协议主要功能的基础上减少对RAM 的占用。

老版QQ原生表情gif动态

这是老版的QQ表情,不过全是动态的的,Windows照片查看器是不会动的,可以右击用浏览器打开查看,再说一遍是老版的,只是分享给宁愿用老版也要动态的人。

Netty学习——Netty解决TCP粘包与拆包问题

TCP 粘包与拆包 TCP是一个“流”协议,TCP底层并不了解上层业务数据的具体含义,它会根据TCP缓冲区的实际情况进行包的划分,所以在业务上认为,一个完整的包可能会被TCP拆分成多个包进行发送,也有可能把多个小包封装成一个大的数据包进行发送,这就是TCP的粘包和拆包问题。 TCP 粘包与拆包问题说明 假设客户端分别发送了俩个数据包D1和D2到服务端。但服务端每次读到的字节数是不确定的,所以可能存在下面四种情况: 服务端分两次读取到了D1和D2数据包,也就是理想的正常情况,没有发生粘包和拆包。 服务端一

胡海龙 4977

深入剖析 Netty 中 TCP 粘包和拆包问题的解决之道

TCP 协议是面向字节流的,这就导致了在数据传输过程中可能会出现 TCP 粘包和拆包的现象,给数据的准确接收和解析带来了挑战。本文将深入探讨 Netty 中解决这一问题的多种策略,并通过详细的代码示例和解释帮助您深入理解。通过合理选择和应用这些策略,并结合精心设计的自定义解码器,开发者能够在 Netty 应用中实现高效、准确的数据传输和处理。我是马丁,一名热衷于深入研究网络编程技术的开发者,经常在 CSDN 平台分享我的技术见解。当数据足够时,读取指定长度的数据包内容,并可以进行后续处理。

持续分享有趣的技术干货 1530

Netty(二)、TCP粘包/拆包问题的解决之道

​ 为了解决TCP粘包/拆包问题导致的半包读写问题,Netty默认提供了多种解码器用于处理半包,只要熟练掌握这些类库的使用,TCP粘包的问题从此变得非常简单,你甚至不用关心他们,这也是其他NIO框架和原生的NIO API所无法匹敌的。在上一章的时间服务器的案例中,就没有考虑读半包的问题,这在功能测试中没有问题,但压力一旦上来了,或者发送大报文之后,就会存在粘包/拆包问题。改动的地方在于,每次应答都会计数。由于上面的例子没有考虑TCP的粘包/拆包问题,所以当发生TCP粘包的时候,我们的程序就不能正常工作了。

weixin_55730337的博客 1465

Netty如何解决TCP粘包/拆包问题?

TCP底层并不了解上层业务数据的具体含义,它会根据TCP缓冲区的实际情况进行包的划分,所以在业务上认为,一个完整的包可能会被TCP拆分成多个包进行发送,也有可能把多个小的包封装成一个大的数据包发送,这就是所谓的TCP粘包和拆包问题。造成TCP协议粘包/拆包问题的原因是TCP协议数据传输是基于字节流的,它不包含消息、数据包等概念,是无界的,需要应用层协议自己设计消息的边界,即消息帧(Message Framing)。1.消息长度固定,累计读取到长度和为定长LEN的报文后,就认为读取到了一个完整的信息。

yanboshuju的博客 914

在使用Netty的时候TCP粘包拆包问题如何解决?

这些代码示例展示了如何在 Netty 中使用不同的解码器来解决 TCP 粘包和拆包问题。选择合适的解决方案取决于具体的应用场景和通信协议。通常情况下,消息定长和消息分隔符是比较常用和简单的解决方法,而消息头部长度表示则提供了更为灵活的方式来处理不同长度的消息。Netty 提供的解码器则是在实际开发中常用的工具,可以有效地解决 TCP 粘包和拆包问题。

初学者 1694

Netty解决TCP粘包和拆包问题的四种方案

在RPC框架中,TCP粘包和拆包问题是必须解决一个问题,因为RPC框架中,各个微服务相互之间都是维系了一个TCP长连接,比如dubbo就是一个全双工的长连接。由于微服务往对方发送信息的时候,所有的请求都是使用的同一个连接,这样就会产生粘包和拆包的问题。本文首先会对TCP粘包和拆包问题进行描述,然后介绍其常用的解决方案,最后会对Netty提供的几种解决方案进行讲解。这...

测试 915

java - netty解决TCP粘包和拆包问题

一,前言 在RPC框架中,TCP粘包和拆包问题是必须解决一个问题,因为RPC框架中,各个微服务相互之间都是维系了一个TCP长连接,比如dubbo就是一个全双工的长连接。由于微服务往对方发送信息的时候,所有的请求都是使用的同一个连接,这样就会产生粘包和拆包的问题。本文首先会对TCP粘包和拆包问题进行描述,然后介绍其常用的解决方案,最后会对Netty提供的几种解决方案进行讲解。 二,正文 1,粘包和拆包 产生TCP粘包和拆包问题的主要原因是,操作系统在发送TCP数据的时候,底层会有一个缓冲区,例如1024个字节

saienenen的博客 1330

【Netty权威指南】04-TCP粘包/拆包问题的解决之道

1、TCP粘包/拆包 TCP是个“流”协议,所谓流,就是没有界限的一串数据。大家可以想想河里的流水它们是连成一片的,其间并没有分界线。TCP底层并不了解上层业务数据的具体含义,它会根据TCP缓冲区的实际情况进行包的划分,所以在业务上认为,一个完整的包可能会被TCP拆分成多个包进行发送,也有可能把多个小的包封装成一个大的数据包发送,这就是所谓的TCP粘包和拆包问题。 1.1、TCP粘包/拆包问题...

通往神秘的道路的专栏 835
上一篇: 使用Netty实现服务端与客户端之间的通信
下一篇: Netty应用HTTP协议实现文件服务器
is_Peng
博客等级 码龄8年 25粉丝 97原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值