diff --git a/.idea/misc.xml b/.idea/misc.xml index 04e58ef..be09ff0 100644 --- a/.idea/misc.xml +++ b/.idea/misc.xml @@ -10,7 +10,7 @@ - + \ No newline at end of file diff --git a/netty/service/pom.xml b/netty/service/pom.xml index d3b78eb..6a50c21 100644 --- a/netty/service/pom.xml +++ b/netty/service/pom.xml @@ -106,6 +106,15 @@ false + + org.apache.maven.plugins + maven-compiler-plugin + + 21 + 21 + --enable-preview + + diff --git a/netty/service/src/main/java/cn/bunny/service/netty/Start01.java b/netty/service/src/main/java/cn/bunny/service/netty/Start01.java new file mode 100644 index 0000000..165169c --- /dev/null +++ b/netty/service/src/main/java/cn/bunny/service/netty/Start01.java @@ -0,0 +1,45 @@ +package cn.bunny.service.netty; + +import io.netty.bootstrap.ServerBootstrap; +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.nio.NioServerSocketChannel; +import io.netty.channel.socket.nio.NioSocketChannel; +import io.netty.handler.codec.string.StringDecoder; + +import static java.lang.StringTemplate.STR; + +public class Start01 { + public static void main(String[] args) { + // 启动器 + new ServerBootstrap() + // 添加组件 NioEventLoopGroup WorkerEventLoop + .group(new NioEventLoopGroup()) + // 选择 ServerNio 实现,还支持某种Linux的实现 + .channel(NioServerSocketChannel.class) + // 处理字节进行分工,需要处理哪些逻辑,决定了 child可以执行哪些操作 + .childHandler( + // 代码客户端读写通道 添加别的 handler + new ChannelInitializer() { + @Override + protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception { + // 添加解码,将传输过来的 ByteBuffer 转为字符串 + nioSocketChannel.pipeline().addLast(new StringDecoder()); + // 自定处理器 + nioSocketChannel.pipeline().addLast(new ChannelInboundHandlerAdapter() { + // 发生读事件 + @Override + public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { + // 打印上一步转化好的字符串 + System.out.println(STR."消息为\{msg}"); + super.channelRead(ctx, msg); + } + }); + } + }) + // 绑定端口 + .bind(8080); + } +}