netty 监听多个udp端口_Netty笔记(一)

本文介绍了Netty作为一个强大的NIO框架,如何简化TCP和UDP Socket开发。重点讨论了Netty的核心组件如EventLoop、Channel、ChannelPipeline和ChannelHandler,并展示了如何在客户端和服务器端实现多UDP端口监听的数据传输业务逻辑。
摘要由CSDN通过智能技术生成

字节跳动就是我心中的耶路撒冷!

netty介绍:

    Netty是一个NIO框架,使用它可以简单快速地开发网络应用程序,比如客户端和服务端的协议。Netty大大简化了网络程序的开发过程比如TCP和UDP的 Socket的开发。

23f0edd4b609da82f916e87a50ffcafc.gif

netty最核心的组件:
  1. EventLoop 

  2. Event

  3. Channel

  4. ChannelPipeline

  5. ChannelHandler

  6. ChannelContextHandler  

netty的组件

Bootstrap:

netty的辅助启动器,netty客户端和服务器的入口,Bootstrap是创建客户端连接的启动器,ServerBootstrap是监听服务端端口的启动器,跟tomcat的Bootstrap类似,程序的入口。

  Channel:

关联jdk原生socket的组件,常用的是NioServerSocketChannel和NioSocketChannel,NioServerSocketChannel负责监听一个tcp端口,有连接进来通过boss reactor创建一个NioSocketChannel将其绑定到worker reactor,然后worker reactor负责这个NioSocketChannel的读写等io事件。

A nexus to a network socket or a component which is capable of I/O operations such as read, write, connect, and bind.A channel provides a user:*   the current state of the channel (e.g. is it open? is it connected?),*   the [configuration parameters](https://netty.io/4.1/api/io/netty/channel/ChannelConfig.html "interface in io.netty.channel") of the channel (e.g. receive buffer size),*   the I/O operations that the channel supports (e.g. read, write, connect, and bind), and*   the [`ChannelPipeline`](https://netty.io/4.1/api/io/netty/channel/ChannelPipeline.html "interface in io.netty.channel") which handles all I/O events and requests associated with the channel.
EventLoop: netty最核心的几大组件之一,就是我们常说的 reactor ,人为划分为 boss reactor 和 worker reactor 。 通过 EventLoopGroup ( Bootstrap 启动时会设置 EventLoopGroup )生成,最常用的是nio的 NioEventLoop ,就如同 EventLoop 的名字, EventLoop 内部有一个无限循环,维护了一个 selector ,处理所有注册到 selector 上的 io 操作,在这里实现了一个线程维护多条连接的工作。 ChannelPipeline:

netty最核心的几大组件之一,ChannelHandler的容器,netty处理io操作的通道,与ChannelHandler组成责任链。write、read、connect等所有的io操作都会通过这个ChannelPipeline,依次通过ChannelPipeline上面的ChannelHandler处理,这就是netty事件模型的核心。ChannelPipeline内部有两个节点,head和tail,分别对应着ChannelHandler链的头和尾。

A list of ChannelHandlers which handles or intercepts inbound events and outbound operations of a Channel.ChannelPipeline implements an advanced form of the Intercepting Filter pattern to give a user full control over how an event is handled and how the ChannelHandlers in a pipeline interact with each other.
ChannelHandler: netty 最核心的几大组件之一, netty 处理 io 事件真正的处理单元,开发者可以创建自己的 ChannelHandler 来处理自己的逻辑,完全控制事件的处理方式。 ChannelHandler 和 ChannelPipeline 组成责任链,使得一组 ChannelHandler 像一条链一样执行下去。 ChannelHandler 分为 inBound 和 outBound ,分别对应 io 的 read 和 write 的执行链。 ChannelHandler 用 ChannelHandlerContext 包裹着,有 prev 和 next 节点,可以获取前后 ChannelHandler , read 时从 ChannelPipeline 的 head 执行到 tail , write 时从 tail 执行到 head ,所以 head 既是 re ad 事件的起点也是 write 事件的终点,与 io 交互最紧密。
使用ChannelHandlerContext在handler之间传递事件public class MyInboundHandler extends ChannelInboundHandlerAdapter {
          @Override     public void channelActive(ChannelHandlerContext ctx) {
             System.out.println("Connected!");         ctx.fireChannelActive();     } } public class MyOutboundHandler extends ChannelOutboundHandlerAdapter {
          @Overri
要在Spring Boot中使用Netty监听多个UDP端口,可以按照以下步骤: 1. 导入Netty和Spring Boot的依赖 ```xml <dependency> <groupId>io.netty</groupId> <artifactId>netty-all</artifactId> <version>4.1.52.Final</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> ``` 2. 创建UDP服务器的配置类 ```java @Configuration public class UdpServerConfig { @Value("${udp.server.port}") private int port; @Value("${udp.server2.port}") private int port2; @Bean(name = "udpServer") public DatagramChannel udpServer() throws Exception { EventLoopGroup group = new NioEventLoopGroup(); DatagramChannel channel = DatagramChannel.open(); channel.bind(new InetSocketAddress(port)); channel.configureBlocking(false); channel.register(group, SelectionKey.OP_READ); return channel; } @Bean(name = "udpServer2") public DatagramChannel udpServer2() throws Exception { EventLoopGroup group = new NioEventLoopGroup(); DatagramChannel channel = DatagramChannel.open(); channel.bind(new InetSocketAddress(port2)); channel.configureBlocking(false); channel.register(group, SelectionKey.OP_READ); return channel; } @PreDestroy public void destroy() { udpServer().close(); udpServer2().close(); } } ``` 该配置类中创建了两个UDP服务器,分别监听不同的端口。其中,通过`@Value`注解注入了端口号,这里使用了`udp.server.port`和`udp.server2.port`两个属性。 3. 创建UDP服务器的处理类 ```java @Component public class UdpServerHandler implements ChannelInboundHandler { @Autowired @Qualifier("udpServer") private DatagramChannel udpServer; @Autowired @Qualifier("udpServer2") private DatagramChannel udpServer2; @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { DatagramPacket packet = (DatagramPacket) msg; // TODO: 处理UDP消息 } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { cause.printStackTrace(); ctx.close(); } } ``` 该类中注入了之前创建的两个UDP服务器,通过`channelRead`方法处理UDP消息。这里使用了`@Component`注解将该类交由Spring管理。 4. 配置Spring Boot应用的属性 在`application.properties`中配置UDP服务器的端口号: ```properties udp.server.port=8888 udp.server2.port=9999 ``` 5. 启动Spring Boot应用 在Spring Boot应用启动时,Netty将会自动创建两个UDP服务器,分别监听`8888`和`9999`端口。可以在`UdpServerHandler`类中编写UDP消息的处理逻辑。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值