在springboot工程中集成netty框架实现UDP通信,在CommandLineRunner的初始化启动时启动两个UDP监听服务。
实例如下
1、两个NettyUdpServer
@Slf4j
@Component
@EnableAsync
public class NettyUdpServer {
@Autowired
NettyServerHandlerInitializer nettyServerHandlerInitializer;
@Async
public void init(int port) {
//表示服务器连接监听线程组,专门接受 accept 新的客户端client 连接
EventLoopGroup bossLoopGroup = new NioEventLoopGroup();
try {
//1、创建netty bootstrap 启动类
Bootstrap serverBootstrap = new Bootstrap();
//2、设置boostrap 的eventLoopGroup线程组
serverBootstrap.group(bossLoopGroup)
//3、设置NIO UDP连接通道
.channel(NioDatagramChannel.class)
// 设置 Netty Server 的端口
.localAddress(new InetSocketAddress(port))
//4、设置通道参数 SO_BROADCAST广播形式
.option(ChannelOption.SO_BROADCAST, true)
//5、设置处理类 装配流水线
.handler(nettyServerHandlerInitializer);
//6、绑定server,通过调用sync()方法异步阻塞,直到绑定成功
ChannelFuture channelFuture = serverBootstrap.bind().sync();
log.info("started and listened on " + channelFuture.channel().localAddress());
//7、监听通道关闭事件,应用程序会一直等待,直到channel关闭
channelFuture.channel().closeFuture().sync();
} catch (Exception e) {
} finally {
log.info("netty udp close!", "info");
//8 关闭EventLoopGroup,
bossLoopGroup.shutdownGracefully();
}
}
}
@Slf4j
@Component
@EnableAsync
public class NettyUdpServer2 {
SpringBoot集成Netty实现UDP通信

本文介绍如何在SpringBoot项目中集成Netty框架来实现UDP通信,并演示了如何在启动时初始化两个UDP监听服务。包括NettyServerHandlerInitializer、SimpleChannelInboundHandler等组件的使用。
最低0.47元/天 解锁文章
8422





