From fce4de27313898f7a575cd36b4970629f49cb95d Mon Sep 17 00:00:00 2001 From: ipipman Date: 2022年1月19日 21:44:41 +0800 Subject: [PATCH 1/2] add netty tcp client to server logic in spring boot sample --- springboot-netty-sample/pom.xml | 13 +++- .../springboot/sample/echo/EchoClient.java | 48 ++++++++++++ .../sample/echo/EchoClientHandler.java | 78 +++++++++++++++++++ .../springboot/sample/echo/EchoServer.java | 52 +++++++++++++ .../sample/echo/EchoServerHandler.java | 54 +++++++++++++ 5 files changed, 244 insertions(+), 1 deletion(-) create mode 100644 springboot-netty-sample/src/main/java/com/ipman/netty/springboot/sample/echo/EchoClient.java create mode 100644 springboot-netty-sample/src/main/java/com/ipman/netty/springboot/sample/echo/EchoClientHandler.java create mode 100644 springboot-netty-sample/src/main/java/com/ipman/netty/springboot/sample/echo/EchoServer.java create mode 100644 springboot-netty-sample/src/main/java/com/ipman/netty/springboot/sample/echo/EchoServerHandler.java diff --git a/springboot-netty-sample/pom.xml b/springboot-netty-sample/pom.xml index c82f779..d27b746 100644 --- a/springboot-netty-sample/pom.xml +++ b/springboot-netty-sample/pom.xml @@ -5,7 +5,7 @@ org.springframework.boot spring-boot-starter-parent - 2.6.2 + 2.4.1 com.example @@ -13,9 +13,13 @@ 0.0.1-SNAPSHOT springboot-netty-sample Demo project for Spring Boot + 1.8 + 1.8 + + org.springframework.boot @@ -27,6 +31,13 @@ spring-boot-starter-test test + + + + io.netty + netty-all + 4.1.39.Final + diff --git a/springboot-netty-sample/src/main/java/com/ipman/netty/springboot/sample/echo/EchoClient.java b/springboot-netty-sample/src/main/java/com/ipman/netty/springboot/sample/echo/EchoClient.java new file mode 100644 index 0000000..6318b40 --- /dev/null +++ b/springboot-netty-sample/src/main/java/com/ipman/netty/springboot/sample/echo/EchoClient.java @@ -0,0 +1,48 @@ +package com.ipman.netty.springboot.sample.echo; + +import io.netty.bootstrap.Bootstrap; +import io.netty.channel.*; +import io.netty.channel.nio.NioEventLoopGroup; +import io.netty.channel.socket.SocketChannel; +import io.netty.channel.socket.nio.NioSocketChannel; +import io.netty.handler.logging.LogLevel; +import io.netty.handler.logging.LoggingHandler; + +/** + * Created by ipipman on 2022年1月19日. + * + * @version V1.0 + * @Package com.ipman.netty.springboot.sample.echo + * @Description: (用一句话描述该文件做什么) + * @date 2022年1月19日 9:26 下午 + */ +public class EchoClient { + + public static void main(String[] args) { + EventLoopGroup group = new NioEventLoopGroup(); + EchoClientHandler clientHandler = new EchoClientHandler(); + try { + Bootstrap b = new Bootstrap(); + b.group(group) + .channel(NioSocketChannel.class) + .option(ChannelOption.TCP_NODELAY, true) + .handler(new ChannelInitializer() { + @Override + public void initChannel(SocketChannel ch) throws Exception { + ChannelPipeline p = ch.pipeline(); + p.addLast(new LoggingHandler(LogLevel.INFO)); + p.addLast(clientHandler); + } + }); + // 连接server端 + ChannelFuture cf = b.connect("127.0.0.1", 8090).sync(); + // 等待连接关闭 + cf.channel().closeFuture().sync(); + } catch (Exception e) { + e.printStackTrace(); + } finally { + group.shutdownGracefully(); + } + + } +} diff --git a/springboot-netty-sample/src/main/java/com/ipman/netty/springboot/sample/echo/EchoClientHandler.java b/springboot-netty-sample/src/main/java/com/ipman/netty/springboot/sample/echo/EchoClientHandler.java new file mode 100644 index 0000000..6289138 --- /dev/null +++ b/springboot-netty-sample/src/main/java/com/ipman/netty/springboot/sample/echo/EchoClientHandler.java @@ -0,0 +1,78 @@ +package com.ipman.netty.springboot.sample.echo; + +import io.netty.buffer.ByteBuf; +import io.netty.buffer.Unpooled; +import io.netty.channel.ChannelHandler.Sharable; +import io.netty.channel.ChannelHandlerContext; +import io.netty.channel.ChannelInboundHandlerAdapter; + +import java.nio.charset.StandardCharsets; +import java.util.concurrent.TimeUnit; + +/** + * Created by ipipman on 2022年1月19日. + * + * @version V1.0 + * @Package com.ipman.netty.springboot.sample.echo + * @Description: (用一句话描述该文件做什么) + * @date 2022年1月19日 9:26 下午 + */ +@Sharable +public class EchoClientHandler extends ChannelInboundHandlerAdapter { + + private final ByteBuf firstMsg; + + public EchoClientHandler() { + firstMsg = Unpooled.wrappedBuffer("Hello Codeing".getBytes(StandardCharsets.UTF_8)); + } + + /** + * 通道活跃时 + * + * @param ctx + * @throws Exception + */ + @Override + public void channelActive(ChannelHandlerContext ctx) throws Exception { + // 第一次传输 + ctx.writeAndFlush(firstMsg); + } + + /** + * 读取数据时 + * + * @param ctx + * @param msg + * @throws Exception + */ + @Override + public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { + ctx.write(msg); + } + + /** + * 读取完毕时 + * + * @param ctx + * @throws Exception + */ + @Override + public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { + // 延迟3秒 + TimeUnit.SECONDS.sleep(3); + ctx.flush(); + } + + /** + * 捕获到异常时 + * + * @param ctx + * @param cause + * @throws Exception + */ + @Override + public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { + cause.printStackTrace(); + ctx.close(); + } +} diff --git a/springboot-netty-sample/src/main/java/com/ipman/netty/springboot/sample/echo/EchoServer.java b/springboot-netty-sample/src/main/java/com/ipman/netty/springboot/sample/echo/EchoServer.java new file mode 100644 index 0000000..bb03580 --- /dev/null +++ b/springboot-netty-sample/src/main/java/com/ipman/netty/springboot/sample/echo/EchoServer.java @@ -0,0 +1,52 @@ +package com.ipman.netty.springboot.sample.echo; + +import io.netty.bootstrap.ServerBootstrap; +import io.netty.channel.ChannelFuture; +import io.netty.channel.ChannelInitializer; +import io.netty.channel.ChannelPipeline; +import io.netty.channel.EventLoopGroup; +import io.netty.channel.nio.NioEventLoopGroup; +import io.netty.channel.socket.SocketChannel; +import io.netty.channel.socket.nio.NioServerSocketChannel; +import io.netty.handler.logging.LogLevel; +import io.netty.handler.logging.LoggingHandler; + +/** + * Created by ipipman on 2022年1月19日. + * + * @version V1.0 + * @Package com.ipman.netty.springboot.sample.http + * @Description: (用一句话描述该文件做什么) + * @date 2022年1月19日 9:09 下午 + */ +public class EchoServer { + + public static void main(String[] args) { + // 创建Server端 + EventLoopGroup workGroup = new NioEventLoopGroup(); + final EchoServerHandler serverHandler = new EchoServerHandler(); + try { + ServerBootstrap b = new ServerBootstrap(); + b.group(workGroup) + .channel(NioServerSocketChannel.class) + .handler(new LoggingHandler(LogLevel.INFO)) + .childHandler(new ChannelInitializer() { + @Override + public void initChannel(SocketChannel ch) throws Exception { + ChannelPipeline p = ch.pipeline(); + p.addLast(new LoggingHandler(LogLevel.INFO)); + p.addLast(serverHandler); + } + }); + // 绑定端口 + ChannelFuture f = b.bind(8090).sync(); + // 等待连接关闭 + f.channel().closeFuture().sync(); + } catch (InterruptedException e) { + e.printStackTrace(); + } finally { + // 关闭所有线程 + workGroup.shutdownGracefully(); + } + } +} diff --git a/springboot-netty-sample/src/main/java/com/ipman/netty/springboot/sample/echo/EchoServerHandler.java b/springboot-netty-sample/src/main/java/com/ipman/netty/springboot/sample/echo/EchoServerHandler.java new file mode 100644 index 0000000..c58b990 --- /dev/null +++ b/springboot-netty-sample/src/main/java/com/ipman/netty/springboot/sample/echo/EchoServerHandler.java @@ -0,0 +1,54 @@ +package com.ipman.netty.springboot.sample.echo; + +import io.netty.channel.ChannelHandler.Sharable; +import io.netty.channel.ChannelHandlerContext; +import io.netty.channel.ChannelInboundHandlerAdapter; + +/** + * Created by ipipman on 2022年1月19日. + * + * @version V1.0 + * @Package com.ipman.netty.springboot.sample.http + * @Description: (用一句话描述该文件做什么) + * @date 2022年1月19日 9:11 下午 + */ +@Sharable +public class EchoServerHandler extends ChannelInboundHandlerAdapter { + + + /** + * 读取 + * + * @param ctx + * @param msg + * @throws Exception + */ + @Override + public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { + ctx.write(msg); + } + + /** + * 读取完毕时 + * + * @param ctx + * @throws Exception + */ + @Override + public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { + ctx.flush(); + } + + /** + * 抓住异常 + * + * @param ctx + * @param cause + * @throws Exception + */ + @Override + public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { + cause.printStackTrace(); + ctx.close(); + } +} From 79a63772ffb3ec8abe0734f345f01c59b8df28f4 Mon Sep 17 00:00:00 2001 From: ipipman Date: 2022年1月19日 22:08:33 +0800 Subject: [PATCH 2/2] add netty http server in spring boot sample --- .../springboot/sample/http/HttpServer.java | 55 +++++++++++++++++ .../sample/http/HttpServerHandler.java | 60 +++++++++++++++++++ 2 files changed, 115 insertions(+) create mode 100644 springboot-netty-sample/src/main/java/com/ipman/netty/springboot/sample/http/HttpServer.java create mode 100644 springboot-netty-sample/src/main/java/com/ipman/netty/springboot/sample/http/HttpServerHandler.java diff --git a/springboot-netty-sample/src/main/java/com/ipman/netty/springboot/sample/http/HttpServer.java b/springboot-netty-sample/src/main/java/com/ipman/netty/springboot/sample/http/HttpServer.java new file mode 100644 index 0000000..dcb2d67 --- /dev/null +++ b/springboot-netty-sample/src/main/java/com/ipman/netty/springboot/sample/http/HttpServer.java @@ -0,0 +1,55 @@ +package com.ipman.netty.springboot.sample.http; + +import io.netty.bootstrap.ServerBootstrap; +import io.netty.channel.*; +import io.netty.channel.nio.NioEventLoopGroup; +import io.netty.channel.socket.SocketChannel; +import io.netty.channel.socket.nio.NioServerSocketChannel; +import io.netty.handler.codec.http.HttpServerCodec; +import io.netty.handler.codec.http.HttpServerExpectContinueHandler; +import io.netty.handler.logging.LogLevel; +import io.netty.handler.logging.LoggingHandler; + +/** + * Created by ipipman on 2022年1月19日. + * + * @version V1.0 + * @Package com.ipman.netty.springboot.sample.http + * @Description: (用一句话描述该文件做什么) + * @date 2022年1月19日 10:00 下午 + */ +public class HttpServer { + + public static void main(String[] args) { + // 主从模式 + EventLoopGroup bossGroup = new NioEventLoopGroup(1); + EventLoopGroup workerGroup = new NioEventLoopGroup(); + + try { + ServerBootstrap b = new ServerBootstrap(); + b.group(bossGroup, workerGroup) + .channel(NioServerSocketChannel.class) + .handler(new LoggingHandler(LogLevel.INFO)) + .childHandler(new ChannelInitializer() { + @Override + protected void initChannel(SocketChannel ch) throws Exception { + // HTTP 模式 + ChannelPipeline p = ch.pipeline(); + p.addLast(new HttpServerCodec()); + p.addLast(new HttpServerExpectContinueHandler()); + p.addLast(new HttpServerHandler()); + } + }); + ChannelFuture ch = b.bind(8099).sync(); + + System.out.println("Open Http Server : http://127.0.0.1:8099"); + ch.channel().closeFuture().sync(); + + } catch (Exception ex) { + ex.printStackTrace(); + } finally { + workerGroup.shutdownGracefully(); + bossGroup.shutdownGracefully(); + } + } +} diff --git a/springboot-netty-sample/src/main/java/com/ipman/netty/springboot/sample/http/HttpServerHandler.java b/springboot-netty-sample/src/main/java/com/ipman/netty/springboot/sample/http/HttpServerHandler.java new file mode 100644 index 0000000..d0e4bf8 --- /dev/null +++ b/springboot-netty-sample/src/main/java/com/ipman/netty/springboot/sample/http/HttpServerHandler.java @@ -0,0 +1,60 @@ +package com.ipman.netty.springboot.sample.http; + +import io.netty.buffer.Unpooled; +import io.netty.channel.ChannelFuture; +import io.netty.channel.ChannelHandler.Sharable; +import io.netty.channel.ChannelHandlerContext; +import io.netty.channel.SimpleChannelInboundHandler; +import io.netty.handler.codec.http.*; + +import java.nio.charset.StandardCharsets; + +import static io.netty.handler.codec.http.HttpResponseStatus.OK; +import static io.netty.handler.codec.http.HttpHeaderNames.CONTENT_TYPE; +import static io.netty.handler.codec.http.HttpHeaderNames.CONTENT_LENGTH; +import static io.netty.handler.codec.http.HttpHeaderValues.TEXT_PLAIN; + + +/** + * Created by ipipman on 2022年1月19日. + * + * @version V1.0 + * @Package com.ipman.netty.springboot.sample.http + * @Description: (用一句话描述该文件做什么) + * @date 2022年1月19日 9:50 下午 + */ +@Sharable +public class HttpServerHandler extends SimpleChannelInboundHandler { + + private static final byte[] CONTEXT = "hello coding".getBytes(StandardCharsets.UTF_8); + + /** + * 当读取完毕时 + * + * @param ctx + * @throws Exception + */ + @Override + public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { + ctx.flush(); + } + + @Override + protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception { + if (msg instanceof HttpRequest) { + HttpRequest req = (HttpRequest) msg; + FullHttpResponse response = new DefaultFullHttpResponse(req.protocolVersion(), OK, Unpooled.wrappedBuffer(CONTEXT)); + response.headers() + .set(CONTENT_TYPE, TEXT_PLAIN) + .set(CONTENT_LENGTH, response.content().readableBytes()); + + ChannelFuture f = ctx.write(response); + } + } + + @Override + public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { + cause.printStackTrace(); + ctx.close(); + } +}

AltStyle によって変換されたページ (->オリジナル) /