| src/main/java/com/genersoft/iot/vmp/netty/config/SysConfig.java | ●●●●● patch | view | raw | blame | history | |
| src/main/java/com/genersoft/iot/vmp/netty/event/StartupEvent.java | ●●●●● patch | view | raw | blame | history | |
| src/main/java/com/genersoft/iot/vmp/netty/handle/UdpServerHandler.java | ●●●●● patch | view | raw | blame | history | |
| src/main/java/com/genersoft/iot/vmp/netty/server/UdpServer.java | ●●●●● patch | view | raw | blame | history | |
| src/main/resources/application.yml | ●●●●● patch | view | raw | blame | history | |
| src/main/resources/logback-spring-local.xml | ●●●●● patch | view | raw | blame | history |
src/main/java/com/genersoft/iot/vmp/netty/config/SysConfig.java
New file @@ -0,0 +1,26 @@ package com.genersoft.iot.vmp.netty.config; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; /** * netty 相关配置信息 * @author zhongrj * @date 2023-02-21 */ @Component @ConfigurationProperties(prefix="syscfg") public class SysConfig { /** * UDP消息接收端口 */ private int UdpReceivePort; public int getUdpReceivePort() { return UdpReceivePort; } public void setUdpReceivePort(int udpReceivePort) { UdpReceivePort = udpReceivePort; } } src/main/java/com/genersoft/iot/vmp/netty/event/StartupEvent.java
New file @@ -0,0 +1,39 @@ package com.genersoft.iot.vmp.netty.event; import com.genersoft.iot.vmp.netty.config.SysConfig; import com.genersoft.iot.vmp.netty.server.UdpServer; import org.junit.platform.commons.logging.Logger; import org.junit.platform.commons.logging.LoggerFactory; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationListener; import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.stereotype.Component; /** * netty udp 服务启动监听 * @author zhongrj * @date 2023-02-21 */ @Component public class StartupEvent implements ApplicationListener<ContextRefreshedEvent> { private static ApplicationContext context; @Override public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) { try { context = contextRefreshedEvent.getApplicationContext(); SysConfig sysConfig = (SysConfig) context.getBean(SysConfig.class); //获取 udpServer UdpServer udpServer = (UdpServer)StartupEvent.getBean(UdpServer.class); //开启 udpServer.run(sysConfig.getUdpReceivePort()); } catch (Exception e) { e.printStackTrace(); } } public static Object getBean(Class beanName) { return context != null ? context.getBean(beanName) : null; } } src/main/java/com/genersoft/iot/vmp/netty/handle/UdpServerHandler.java
New file @@ -0,0 +1,45 @@ package com.genersoft.iot.vmp.netty.handle; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import io.netty.channel.socket.DatagramPacket; import io.netty.util.CharsetUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; /** * updHandler udp 服务端数据接收处理 * @author zhongrj * @date 2023-02-21 */ @Component public class UdpServerHandler extends SimpleChannelInboundHandler<DatagramPacket> { private Logger logger = LoggerFactory.getLogger(this.getClass()); @Override protected void channelRead0(ChannelHandlerContext channelHandlerContext, DatagramPacket datagramPacket) throws Exception { // 读取收到的数据 ByteBuf buf = (ByteBuf) datagramPacket.copy().content(); byte[] req = new byte[buf.readableBytes()]; buf.readBytes(req); String body = new String(req, CharsetUtil.UTF_8); System.out.println("【UDP】>>>>>> 收到客户端的数据:"+body); } //捕获异常 @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)throws Exception { logger.error("UdpServerHandler exceptionCaught"+cause.getMessage()); System.out.println("UdpServerHandler exceptionCaught"+cause.getMessage()); cause.printStackTrace(); ctx.close(); } //消息没有结束的时候触发 @Override public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { ctx.flush(); } } src/main/java/com/genersoft/iot/vmp/netty/server/UdpServer.java
New file @@ -0,0 +1,84 @@ package com.genersoft.iot.vmp.netty.server; import com.genersoft.iot.vmp.netty.handle.UdpServerHandler; import io.netty.bootstrap.Bootstrap; import io.netty.channel.*; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioDatagramChannel; import io.netty.handler.codec.string.StringDecoder; import io.netty.handler.codec.string.StringEncoder; import io.netty.util.concurrent.DefaultEventExecutorGroup; import io.netty.util.concurrent.EventExecutorGroup; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; /** * updServer udp服务端 * @author zhongrj * @date 2023-02-21 */ @Component public class UdpServer { private static Logger LOG = LoggerFactory.getLogger(UdpServer.class); //给管道抽象出接口,给Channel更多的能力和配置,例如Channel的状态,参数,IO操作 //使用ChannelPipeline实现自定义IO //Channel channel; public void run(int port) { Thread thread = new Thread(new Runnable() { @Override public void run() { //InetSocketAddress socketAddress = new InetSocketAddress("s16s652780.51mypc.cn", 21403); //启动服务 EventLoopGroup workerGroup = new NioEventLoopGroup(); //优化使用的线程 final EventExecutorGroup group = new DefaultEventExecutorGroup(16); try { Bootstrap b = new Bootstrap();//udp不能使用ServerBootstrap b.group(workerGroup).channel(NioDatagramChannel.class)//设置UDP通道 //设置udp的管道工厂 .handler(new ChannelInitializer<NioDatagramChannel>() { //NioDatagramChannel标志着是UDP格式的 @Override protected void initChannel(NioDatagramChannel ch) throws Exception { // TODO Auto-generated method stub //创建一个执行Handler的容器 ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast(new StringDecoder()); pipeline.addLast(new StringEncoder()); //执行具体的自定义处理器 pipeline.addLast(group, "handler", new UdpServerHandler()); } })//初始化处理器 //true / false 多播模式(UDP适用),可以向多个主机发送消息 .option(ChannelOption.SO_BROADCAST, true)// 支持广播 .option(ChannelOption.SO_RCVBUF, 2048 * 1024)// 设置UDP读缓冲区为2M .option(ChannelOption.SO_SNDBUF, 1024 * 1024);// 设置UDP写缓冲区为1M // 绑定端口,开始接收进来的连接 ChannelFuture f = b.bind(port).sync(); //获取channel通道 //channel=f.channel(); System.out.println("UDP Server 启动,端口:"+port); // 等待服务器 socket 关闭 。 // 这不会发生,可以优雅地关闭服务器。 f.channel().closeFuture().sync(); } catch (InterruptedException e) { e.printStackTrace(); } finally { //优雅退出 释放线程池资源 group.shutdownGracefully(); workerGroup.shutdownGracefully(); } } }); thread.start(); } } src/main/resources/application.yml
@@ -1,3 +1,3 @@ spring: profiles: active: dev active: test src/main/resources/logback-spring-local.xml
@@ -94,4 +94,20 @@ <appender-ref ref="RollingFileError"/> <appender-ref ref="druidSqlRollingFile"/> </logger> <!--gb28181包日志的记录--> <logger name="com.genersoft.iot.vmp.gb28181" level="info" additivity="true"> <!--AppenderRef ref="Console"/--> <appender-ref ref="RollingFile"/> <appender-ref ref="RollingFileError"/> <appender-ref ref="druidSqlRollingFile"/> </logger> <!--gb28181包日志的记录--> <logger name="com.genersoft.iot.vmp.netty" level="info" additivity="true"> <!--AppenderRef ref="Console"/--> <appender-ref ref="RollingFile"/> <appender-ref ref="RollingFileError"/> <appender-ref ref="druidSqlRollingFile"/> </logger> </configuration>