From 73b2d51857d5d59891cef6559d19e9a32b171a66 Mon Sep 17 00:00:00 2001 From: bunny <1319900154@qq.com> Date: Fri, 24 May 2024 15:53:29 +0800 Subject: [PATCH] =?UTF-8?q?=E5=AE=8C=E6=88=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../service/netty/demo7/HelloClient.java | 41 +++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 netty/service/src/main/java/cn/bunny/service/netty/demo7/HelloClient.java 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(); + } + } +}