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

现象演示

服务端:

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的粘包半包问题?(上)

上一篇:JS端自己拼接一个表单进行提交:实现下载或者传参后台


下一篇:MySQL WHERE 子句