netty |ハーフパッケージとスティッキーパッケージ現象

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;

public class NettyTes {
    
    
	public static void main(String[] args) throws Exception {
    
    
		start();
	}

	private static void start() throws Exception {
    
    
		Bootstrap bs = new Bootstrap();
		bs.group(new NioEventLoopGroup());
		bs.channel(NioSocketChannel.class).handler(new ChannelInitializer<Channel>() {
    
    

			@Override
			protected void initChannel(Channel ch) throws Exception {
    
    
				ch.pipeline()
				.addLast(new StringEncoder())
				.addLast(new SimpleChannelInboundHandler<String>() {
    
    

					@Override
					protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
    
    
						
					}

					@Override
					public void channelActive(ChannelHandlerContext ctx) throws Exception {
    
    
						int x = 10;
						for (int i = 0; i < 10; i++) {
    
    
							StringBuffer sb = new StringBuffer();
							for (int j = 0; j < x; j++) {
    
    
								sb.append(i);
							}
							ctx.writeAndFlush(sb.toString());
						}
						
					}
					
				});
				
			}
		});
		bs.remoteAddress("127.0.0.1", 9888);
		ChannelFuture future = bs.connect().sync();
		future.channel().closeFuture().sync();
		
	}
}
[2021-03-17 14:38:55 073]  TCP服务器[127.0.0.1:64422]接收10字节: 
[2021-03-17 14:38:55 075]  0123456789
[2021-03-17 14:39:26 084]  TCP服务器[127.0.0.1:65117]接收30字节: 
[2021-03-17 14:39:26 085]  111111111122222222223333333333
[2021-03-17 14:39:26 085]  TCP服务器[127.0.0.1:65117]接收60字节: 
[2021-03-17 14:39:26 086]  444444444455555555556666666666777777777788888888889999999999
[2021-03-17 14:39:26 084]  TCP服务器[127.0.0.1:65117]接收30字节: 
[2021-03-17 14:39:26 085]  11111111112222222222333333333344444
[2021-03-17 14:39:26 085]  TCP服务器[127.0.0.1:65117]接收60字节: 
[2021-03-17 14:39:26 086]  4444455555555556666666666777777777788888888889999999999

おすすめ

転載: blog.csdn.net/dmw412724/article/details/114938641