Springboot前后端通过TCP通信学习总结
在Spring Boot中,前后端通过TCP通信可以使用Netty框架来实现。以下是一个简单的例子,展示了如何在Spring Boot应用中设置Netty服务器,并处理来自客户端的TCP连接和数据。
- 添加依赖到
pom.xml
:
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.69.Final</version>
</dependency>
- 创建Netty服务器配置类:
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
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 org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.net.InetSocketAddress;
@Component
public class NettyTCPServer {
private EventLoopGroup bossGroup = new NioEventLoopGroup();
private EventLoopGroup workerGroup = new NioEventLoopGroup();
private ServerBootstrap bootstrap;
@PostConstruct
public void start() {
bootstrap = new ServerBootstrap();
bootstrap.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.localAddress(new InetSocketAddress("localhost", 8080))
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) {
// 添加自定义的ChannelHandler处理业务逻辑
}
});
try {
bootstrap.bind().sync();
System.out.println("TCP服务器启动在端口: 8080");
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
@PreDestroy
public void stop() {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
- 创建自定义的ChannelHandler处理业务逻辑:
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
public class TCPServerHandler extends SimpleChannelInboundHandler<String> {
@Override
protected void channelRead0(ChannelHandlerContext ctx, String msg) {
// 处理接收到的消息
System.out.println("接收到消息
评论已关闭