Skip to content

Netty TCP 案例

NettyServer

java
public static void main(String[] args) throws InterruptedException {
    // Boos 组,负责轮询监听 Accept 事件
    EventLoopGroup boosGroup = new NioEventLoopGroup();
    // Worker 组,负责处理 Channel 上的事件,如读写事件
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    //启动器
    ServerBootstrap bootstrap = new ServerBootstrap();

    bootstrap.group(boosGroup,workerGroup)
            .channel(NioServerSocketChannel.class)
            .option(ChannelOption.SO_BACKLOG,128)
            .childOption(ChannelOption.SO_KEEPALIVE,true)
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel socketChannel) 
                        throws Exception {
                    //添加 Handler
                    socketChannel.pipeline().addLast(new NettyServerHandler());
                }
            });

    System.out.println("服务器 is ready ...");

    ChannelFuture cf = bootstrap.bind(7668).sync();

    cf.channel().closeFuture().sync();
}

NettyServerHandler

java
public class NettyServerHandler extends ChannelInboundHandlerAdapter {

    //读事件触发
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) 
            throws Exception {
        //将 msg 转成一个 ByteBuf
        ByteBuf buf  = (ByteBuf) msg;
        System.out.println("客户端发送的消息"+buf.toString(CharsetUtil.UTF_8));
        System.out.println("客户端地址:" + ctx.channel().remoteAddress());
    }

    //读事件处理完毕
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) 
            throws Exception {
        //将数据写回客户端
        ByteBuf byteBuf = Unpooled.copiedBuffer("hello,客户端 汪",
                CharsetUtil.UTF_8);
        ctx.writeAndFlush(byteBuf);
    }

}

NettyClient

java
public static void main(String[] args) throws InterruptedException {
    
    EventLoopGroup eventExecutors = new NioEventLoopGroup();

    try {
        Bootstrap bootstrap = new Bootstrap();

        bootstrap.group(eventExecutors)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        socketChannel.pipeline().addLast(new NettyClientHandler());
                    }
                });

        System.out.println("客户端 ok ...");

        ChannelFuture future = bootstrap.connect("127.0.0.1", 7668).sync();
        future.channel().closeFuture().sync();
    }finally {
        eventExecutors.shutdownGracefully();
    }
}

NettyClientHandler

java
public class NettyClientHandler extends ChannelInboundHandlerAdapter {

    //当通道就绪就会触发该方法
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        //发送数据给服务端
        ctx.writeAndFlush(Unpooled.copiedBuffer("hello,server: 喵喵", CharsetUtil.UTF_8));
    }

    //当通道有读取事件
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf buf = (ByteBuf) msg;
        System.out.println("服务器回复的消息是:" + buf.toString(CharsetUtil.UTF_8));
        System.out.println("服务器地址:" + ctx.channel().remoteAddress());
    }
}
  • 案例效果:服务端与客户端实现了消息互通

TCP案例.png