且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Netty如何解决TCP的粘包半包问题?(上)

更新时间:2021-10-16 01:55:01

现象演示

服务端:

public class Server {

    private int port;

    public Server(int port) {
        this.port = port;
    }

    public void start(){
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workGroup = new NioEventLoopGroup();

        ServerBootstrap server = new ServerBootstrap().group(bossGroup,workGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ServerChannelInitializer());

        try {
            ChannelFuture future = server.bind(port).sync();
            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            System.out.println("server start fail");
        }finally {
            bossGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) {
        Server server = new Server(8090);
        server.start();
    }
}

客户端

package io.netty.example.sticky;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

/**
 * @author JavaEdge
 * @date 2021/2/8
 */
public class Client {

    private  int port;
    private  String address;

    public Client(int port, String address) {
        this.port = port;
        this.address = address;
    }

    public void start(){
        EventLoopGroup group = new NioEventLoopGroup();

        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY, true)
                .handler(new ClientChannelInitializer());
        try {
            ChannelFuture future = bootstrap.connect(address,port).sync();
            future.channel().writeAndFlush("Hello world, i'm online");
            future.channel().closeFuture().sync();
        } catch (Exception e) {
            System.out.println("client start fail");
        }finally {
            group.shutdownGracefully();
        }

    }

    public static void main(String[] args) {
        Client client = new Client(8090,"127.0.0.1");
        client.start();
    }
}

粘包现象:

Netty如何解决TCP的粘包半包问题?(上)