一个最小 Netty TCP 示例应说明:服务端绑定地址、客户端连接、消息边界与编码、处理器职责,以及通道和线程组如何关闭。只看到连接成功或截图不能证明业务消息已经往返。
固定依赖与文件位置
本轮使用 JDK 21、Netty 4.1.107.Final 与 JUnit 5。下列共享 POM 由 Spring Boot 3.2.4 的依赖管理固定 Netty;Redis 相关依赖服务于本轮其他示例,不是 TCP 示例的必需部分,也不代表生产推荐版本。把 POM 放在项目根目录,将后面的测试类放在 src/test/java/site/NettyHelloTest.java。
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>3.2.4</version></parent>
<groupId>site.cxykk.examples</groupId><artifactId>phase5-examples</artifactId><version>1.0.0</version>
<properties><java.version>21</java.version><build.dir>${project.basedir}/target</build.dir></properties>
<dependencies>
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId></dependency>
<dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId></dependency>
<dependency><groupId>io.netty</groupId><artifactId>netty-codec</artifactId></dependency>
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency>
</dependencies>
<build><directory>${build.dir}</directory></build>
</project>
完整本地往返测试
服务端绑定 127.0.0.1 的随机端口;双方都按换行符分帧,并使用 UTF-8 字符串编码。服务器收到一行后回写一行,客户端断言内容,再在 finally 中关闭资源。这样不依赖固定端口或额外截图。
package site;
import io.netty.bootstrap.Bootstrap;
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.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class NettyHelloTest {
static void codecs(ChannelPipeline p) {
p.addLast(new LineBasedFrameDecoder(1024));
p.addLast(new StringDecoder(StandardCharsets.UTF_8));
p.addLast(new StringEncoder(StandardCharsets.UTF_8));
}
@Test void loopbackEcho() throws Exception {
var boss = new NioEventLoopGroup(1);
var worker = new NioEventLoopGroup(1);
var clientGroup = new NioEventLoopGroup(1);
Channel server = null, client = null;
var received = new CompletableFuture<String>();
try {
server = new ServerBootstrap().group(boss, worker)
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<SocketChannel>() {
protected void initChannel(SocketChannel ch) {
codecs(ch.pipeline());
ch.pipeline().addLast(new SimpleChannelInboundHandler<String>() {
protected void channelRead0(ChannelHandlerContext ctx, String msg) {
ctx.writeAndFlush(msg + "\n");
}
});
}
}).bind("127.0.0.1", 0).sync().channel();
int port = ((InetSocketAddress) server.localAddress()).getPort();
client = new Bootstrap().group(clientGroup).channel(NioSocketChannel.class)
.handler(new ChannelInitializer<SocketChannel>() {
protected void initChannel(SocketChannel ch) {
codecs(ch.pipeline());
ch.pipeline().addLast(new SimpleChannelInboundHandler<String>() {
protected void channelRead0(ChannelHandlerContext ctx, String msg) {
received.complete(msg);
}
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
received.completeExceptionally(cause);
ctx.close();
}
});
}
}).connect("127.0.0.1", port).sync().channel();
client.writeAndFlush("hello\n").sync();
assertEquals("hello", received.get(5, TimeUnit.SECONDS));
System.out.println("echo=hello; transport=loopback-tcp");
} finally {
if (client != null) client.close().syncUninterruptibly();
if (server != null) server.close().syncUninterruptibly();
clientGroup.shutdownGracefully(0, 2, TimeUnit.SECONDS).syncUninterruptibly();
worker.shutdownGracefully(0, 2, TimeUnit.SECONDS).syncUninterruptibly();
boss.shutdownGracefully(0, 2, TimeUnit.SECONDS).syncUninterruptibly();
}
}
}
mvn -Dtest=NettyHelloTest test
本次实际输出 echo=hello; transport=loopback-tcp,断言核对的是一条消息的内容。TCP 是字节流,不能假设一次 write 对应一次 read;示例的 1024 字节行帧限制也属于协议条件。
测试在无外网容器的回环地址上完成,未暴露宿主端口;没有验证公网通信、TLS、断线重连、背压或吞吐量。业务处理器中的耗时操作也不能照搬为阻塞事件循环的设计。
下一步阅读
历史截图
以下为原资料截图,保留作历史参考,不是本轮验证结果。正文中的文字与示例可独立阅读。





历史资料保留链接:https://blog.csdn.net/Lanna_w/article/details/129351340。