diff --git a/netty/service/src/main/java/cn/bunny/service/netty/demo7/HelloClient.java b/netty/service/src/main/java/cn/bunny/service/netty/demo7/HelloClient.java new file mode 100644 index 0000000..6352c89 --- /dev/null +++ b/netty/service/src/main/java/cn/bunny/service/netty/demo7/HelloClient.java @@ -0,0 +1,41 @@ +package cn.bunny.service.netty.demo7; + +import io.netty.bootstrap.Bootstrap; +import io.netty.buffer.ByteBuf; +import io.netty.channel.ChannelHandlerContext; +import io.netty.channel.ChannelInboundHandlerAdapter; +import io.netty.channel.ChannelInitializer; +import io.netty.channel.nio.NioEventLoopGroup; +import io.netty.channel.socket.SocketChannel; +import io.netty.channel.socket.nio.NioSocketChannel; +import lombok.extern.slf4j.Slf4j; + +@Slf4j +public class HelloClient { + public static void main(String[] args) { + NioEventLoopGroup group = new NioEventLoopGroup(); + try { + Bootstrap bootstrap = new Bootstrap(); + bootstrap.channel(NioSocketChannel.class); + bootstrap.group(group); + bootstrap.handler(new ChannelInitializer() { + @Override + protected void initChannel(SocketChannel socketChannel) throws Exception { + socketChannel.pipeline().addLast(new ChannelInboundHandlerAdapter() { + @Override + public void channelActive(ChannelHandlerContext ctx) throws Exception { + ByteBuf buf = ctx.alloc().buffer(16); + buf.writeBytes(new byte[]{0, 1, 2, 3, 4}); + ctx.writeAndFlush(buf); + ctx.channel().close(); + } + }); + } + }); + } catch (Exception e) { + log.debug("客户端错误:{}", e); + } finally { + group.shutdownGracefully(); + } + } +}