Springboot+Netty搭建UDP服务端

2023-05-16

        UDP是一个无连接协议,应用范围很大,对于一些低功耗的设备可以使用UDP方式向云端推送消息信息,也可以在推送消息时收到从云端原路返回的消息,使用Netty+SpringBoot方式可以快速开发一套基于UDP协议的服务端程序。

        Demo地址:SpringBoot+Netty实现UDP服务端客户端的源码Demo

        新建Springboot的maven项目,pom.xml文件导入依赖包

<?xml version="1.0"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <modelVersion>4.0.0</modelVersion>


	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.0.5.RELEASE</version>
		<relativePath />
	</parent>

	<groupId>boot.base.udp.server</groupId>
	<artifactId>boot-example-base-udp-server-2.0.5</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>boot-example-base-udp-server-2.0.5</name>
	<url>http://maven.apache.org</url>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>

		<!--web模块的启动器 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<!-- netty依赖 springboot2.x自动导入版本 -->
		<dependency>
			<groupId>io.netty</groupId>
			<artifactId>netty-all</artifactId>
		</dependency>
		<dependency>
			<groupId>io.springfox</groupId>
			<artifactId>springfox-swagger2</artifactId>
			<version>2.9.2</version>
		</dependency>
		<dependency>
			<groupId>com.github.xiaoymin</groupId>
			<artifactId>swagger-bootstrap-ui</artifactId>
			<version>1.9.2</version>
		</dependency>
	</dependencies>
	<build>
		<plugins>
			<!-- 打包成一个可执行jar -->
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
				<executions>
					<execution>
						<goals>
							<goal>repackage</goal>
						</goals>
					</execution>
				</executions>
			</plugin>
		</plugins>
	</build>
	
</project>

​

        Springboot启动类,使用异步方式启动一个基于UDP协议的Netty应用(也包含web应用的)

package boot.example.udp.server;


import boot.example.udp.server.server.BootNettyUdpBootstrapThread;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 *  蚂蚁舞
 */
@SpringBootApplication
public class BootNettyUdpApplication {
    public static void main( String[] args ) {

		SpringApplication app = new SpringApplication(BootNettyUdpApplication.class);
		app.run(args);

		BootNettyUdpBootstrapThread thread = new BootNettyUdpBootstrapThread(9999);
		thread.start();
        System.out.println( "Hello World!" );
    }

}

        Netty的UDP启动类

package boot.example.udp.server.server;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioDatagramChannel;

/**
 *  蚂蚁舞
 */
public class BootNettyUdpBootstrapServer extends BootNettyUdpAbstractBootstrapServer {

	private EventLoopGroup eventLoopGroup;
	
	/**
	 * 启动服务
	 */
	public void startup(int port) {
		
		eventLoopGroup = new NioEventLoopGroup(20);
		try {
            Bootstrap serverBootstrap = new Bootstrap();
            serverBootstrap = serverBootstrap.group(eventLoopGroup);
            serverBootstrap = serverBootstrap.channel(NioDatagramChannel.class);
            serverBootstrap = serverBootstrap.option(ChannelOption.SO_BROADCAST, true);
			serverBootstrap = serverBootstrap.handler(new ChannelInitializer<NioDatagramChannel>(){
				@Override
				protected void initChannel(NioDatagramChannel ch) throws Exception {
					initChannelHandler(ch.pipeline());
				}
			});
            ChannelFuture f = serverBootstrap.bind(port).sync();
			if(f.isSuccess()) {
				System.out.println("netty udp start "+port);
				f.channel().closeFuture().sync();
			}
		} catch (Exception e) {
			// TODO: handle exception
		} finally {
			System.out.println("netty udp close!");
			eventLoopGroup.shutdownGracefully();
		}
	}

	/**
	 * 关闭服务
	 */
	public void shutdown() {
		eventLoopGroup.shutdownGracefully();
	}

	
}

BootNettyUdpBootstrap  
package boot.example.udp.server.server;

/**
 * udp 启动接口类
 * 蚂蚁舞
 */
public interface BootNettyUdpBootstrap {

    void startup(int port);

    void shutdown();
    
}

BootNettyUdpAbstractBootstrapServer

package boot.example.udp.server.server;


import io.netty.channel.ChannelPipeline;

/**
 *  蚂蚁舞
 */
public abstract class BootNettyUdpAbstractBootstrapServer implements BootNettyUdpBootstrap {


	void initChannelHandler(ChannelPipeline channelPipeline) {
		channelPipeline.addLast(new BootNettyUdpSimpleChannelInboundHandler());
	}

	
}

     BootNettyUdpBootstrapThread

package boot.example.udp.server.server;


/**
 *  蚂蚁舞
 */
public class BootNettyUdpBootstrapThread extends Thread {

    private final int port;

    public BootNettyUdpBootstrapThread(int port){
        this.port = port;
    }

    public void run() {
        BootNettyUdpBootstrap iotUdpBootstrap = new BootNettyUdpBootstrapServer();
        iotUdpBootstrap.startup(this.port);
    }


}

BootNettyUdpData  
package boot.example.udp.server.server;

/**
 *  蚂蚁舞
 */
public class BootNettyUdpData {

    private String address;

    private String content;

    private long time_stamp;

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public long getTime_stamp() {
        return time_stamp;
    }

    public void setTime_stamp(long time_stamp) {
        this.time_stamp = time_stamp;
    }
}

BootNettyUdpDataCache  
package boot.example.udp.server.server;


import java.util.ArrayList;
import java.util.List;

/**
 *  蚂蚁舞  保存客户端发送的数据,测试demo
 */
public class BootNettyUdpDataCache {

    public static List<BootNettyUdpData> bootNettyUdpDataList = new ArrayList<>();


}

服务端I/O数据读写处理类

package boot.example.udp.server.server;


import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;
import io.netty.util.CharsetUtil;

/**
 *  蚂蚁舞
 */
public class BootNettyUdpSimpleChannelInboundHandler extends SimpleChannelInboundHandler<DatagramPacket> {

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket packet) throws Exception {
		long time_stamp = System.currentTimeMillis()/1000;
		System.out.println("received--data:"+packet.content().toString(CharsetUtil.UTF_8)+"--ip:"+packet.sender().getAddress()+"--port:"+packet.sender().getPort());
        try {
			BootNettyUdpData bootNettyUdpData = new BootNettyUdpData();
			bootNettyUdpData.setAddress(packet.sender().getAddress().toString());
			bootNettyUdpData.setContent(packet.content().toString(CharsetUtil.UTF_8));
			bootNettyUdpData.setTime_stamp(time_stamp);
			BootNettyUdpDataCache.bootNettyUdpDataList.add(bootNettyUdpData);
            ctx.writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer(time_stamp+"", CharsetUtil.UTF_8), packet.sender()));
		} catch (Exception e) {
			ctx.writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer("exception", CharsetUtil.UTF_8), packet.sender()));
			System.out.println("received exception--data:"+packet.content().toString(CharsetUtil.UTF_8)+"--"+e.toString());
		}

	}

}

BootNettyUdpController

package boot.example.udp.server.controller;

import boot.example.udp.server.server.BootNettyUdpData;
import boot.example.udp.server.server.BootNettyUdpDataCache;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * 	蚂蚁舞
 */
@RestController
public class BootNettyUdpController {

	@GetMapping(value = {"", "/"})
	public String index() {
		return "netty springBoot udp server demo";
	}

	@GetMapping("/dataList")
	public List<BootNettyUdpData> clientList() {
		return BootNettyUdpDataCache.bootNettyUdpDataList;
	}


}

     SwaggerConfig UI页面查看数据

package boot.example.udp.server;

import com.google.common.base.Predicates;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

/**
 *  蚂蚁舞
 */
@Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Bean
    public Docket createRestApi(){
        return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).select()
                .apis(RequestHandlerSelectors.any()).paths(PathSelectors.any())
                .paths(Predicates.not(PathSelectors.regex("/error.*")))
                .paths(PathSelectors.regex("/.*"))
                .build().apiInfo(apiInfo());
    }

    private ApiInfo apiInfo(){
        return new ApiInfoBuilder()
                .title("netty udp 服务端demo")
                .description("netty udp 服务端接口测试demo")
                .version("0.01")
                .build();
    }

    /**
     * http://localhost:xxxx/doc.html  地址和端口根据实际项目查看
     */


}

代码的目录结构

├─boot-example-base-udp-server-2.0.5
│  │  pom.xml
│  │  
│  ├─src
│  │  ├─main
│  │  │  ├─java
│  │  │  │  └─boot
│  │  │  │      └─example
│  │  │  │          └─udp
│  │  │  │              └─server
│  │  │  │                  │  BootNettyUdpApplication.java
│  │  │  │                  │  SwaggerConfig.java
│  │  │  │                  │  
│  │  │  │                  ├─controller
│  │  │  │                  │      BootNettyUdpController.java
│  │  │  │                  │      
│  │  │  │                  └─server
│  │  │  │                          BootNettyUdpAbstractBootstrapServer.java
│  │  │  │                          BootNettyUdpBootstrap.java
│  │  │  │                          BootNettyUdpBootstrapServer.java
│  │  │  │                          BootNettyUdpBootstrapThread.java
│  │  │  │                          BootNettyUdpData.java
│  │  │  │                          BootNettyUdpDataCache.java
│  │  │  │                          BootNettyUdpSimpleChannelInboundHandler.java
│  │  │  │                          
│  │  │  └─resources
│  │  │          application.properties
│  │  │          
│  │  └─test
│  │      └─java
│  │          └─boot
│  │              └─example
│  │                  └─udp
│  │                      └─server
│  │                              AppTest.java
│  │                              

启动程序

2023-01-20 13:12:13.140  INFO 2320 --- [           main] o.s.c.support.DefaultLifecycleProcessor  : Starting beans in phase 2147483647
2023-01-20 13:12:13.140  INFO 2320 --- [           main] d.s.w.p.DocumentationPluginsBootstrapper : Context refreshed
2023-01-20 13:12:13.185  INFO 2320 --- [           main] d.s.w.p.DocumentationPluginsBootstrapper : Found 1 custom documentation plugin(s)
2023-01-20 13:12:13.225  INFO 2320 --- [           main] s.d.s.w.s.ApiListingReferenceScanner     : Scanning for api listing references
2023-01-20 13:12:13.438  INFO 2320 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8092 (http) with context path ''
2023-01-20 13:12:13.443  INFO 2320 --- [           main] b.e.udp.server.BootNettyUdpApplication   : Started BootNettyUdpApplication in 6.142 seconds (JVM running for 6.877)
Hello World!
netty udp start 9999

浏览器web访问

http://localhost:8092/doc.html

使用工具发送消息

可以看到服务端收到了udp客户端的消息,同时客户端也收到了服务端返回的时间戳

可以使用一些UDP客户端的软件来测试,这个Demo应用是基于Netty4.x的,对于Netty5.0有一些小的变化,在I/O数据处理类这里的变化需要注意,channelRead0(ChannelHandlerContext, I)方法改成了messageReceived(ChannelHandlerContext, I)},否则代码会报错然后找不到原因,Netty方法源码上是有注释信息的。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Springboot+Netty搭建UDP服务端 的相关文章

随机推荐

  • HX711 24位A/D模块计算公式

    基本原理讲解 100kg 传感器 满量程输出电压 61 激励电压 灵敏度2 0mv v 例如 xff1a 供电电压是5v 乘以灵敏度2 0mv v 61 满量程10mv 相当于有100Kg 重力产生时候产生10mV 的电压 711模块对产生
  • stm32 keil实现串口printf输出中文字符

    添加如下代码 xff0c 可以GNUC的方式实现 span class hljs comment ifdef GNUC span With GCC RAISONANCE small printf option LD Linker gt Li
  • stm32 基于TIM1定时器的PWM输出

    void PWM TIM1 uint16 t arr uint16 t psc RCC APB2PeriphClockCmd RCC APB2Periph TIM1 ENABLE 定时器TIM1时钟使能 TIM DeInit TIM1 设置
  • stm32 can总线参考例程

    CAN初始化 tsjw 重新同步跳跃时间单元 范围 1 3 CAN SJW 1tq CAN SJW 2tq CAN SJW 3tq CAN SJW 4tq tbs2 时间段2的时间单元 范围 1 8 tbs1 时间段1的时间单元 范围 1
  • 物联网IOT-mqtt协议

    MQTT是一种客户机服务器发布 订阅消息传递传输协议 它重量轻 开放 简单 设计简单 易于实现 这些特性使其非常适合在许多情况下使用 xff0c 包括受限的环境 xff0c 如机器间通信 M2M 和物联网 IoT 环境 xff0c 在这些环
  • 联合索引的最左匹配原则的成因

    联合索引的最左匹配原则的成因 上面我们只看的是单一的索引 xff0c 接下来咱们来看看联合索引 xff0c 也就是回答第二个问题 联合索引的最左匹配原则的成因 什么是联合索引呢 xff0c 就是由多列组成的索引了 那亦要了解其成因 xff0
  • 腾讯云轻量服务器的Ubuntu如何使用root(根)用户登陆ssh/Shell/terminal/终端/WindTerm/FinalShell

    Ubuntu 系统的默认用户名是 ubuntu xff0c 并在安装过程中默认不设置 root 帐户和密码 您如有需要 xff0c 可在设置中开启允许 root 用户登录 具体操作步骤如下 xff1a 使用 ubuntu 帐户登录轻量应用服
  • Ubuntu安装sshd服务

    ubuntu安装ssh服务 一 安装shhd SSH分客户端openssh client和openssh server 如果你只是想登陆别的机器的SSH只需要安装openssh client xff08 ubuntu有默认安装 xff0c
  • Linux环境(六)--资源与限制

    资源与限制 运行在Linux系统上的程序是有资源限制的 这些也许是硬件引起的限制 例如内存 xff0c 也许由系统策略引起的限制 例如 xff0c 允许 的CPU时间 xff0c 或者是实现的限制 例如 xff0c 整数的尺寸或是文件名允许
  • 遇到了C/C++控制台程序无法输入中文的情况

    其实C C 43 43 控制台程序无法cin中文的情况并不是你使用了string xff0c string是能输入并保存中文的 xff1b 经过一番探究 xff0c 我发现主要的问题是文件的编码和控制台所处的代码页 xff08 控制台的编码
  • Jpg2Dcm中文乱码问题

    Jpg2Dcm中文乱码问题 最近老板提出了一个新的功能要求 xff0c 希望可以把图片转成dcm 在实现功能的问题中遇见了很多问题和掉过许多坑 于是在此记录下来 问题 xff1a 第一次在进行Jpg2Dcm时 xff0c 可以进行图片转dc
  • 神经网络的数学表达式,神经网络的数学理论

    什么是神经网络 神经网络可以指向两种 xff0c 一个是生物神经网络 xff0c 一个是人工神经网络 生物神经网络 xff1a 一般指生物的大脑神经元 xff0c 细胞 xff0c 触点等组成的网络 xff0c 用于产生生物的意识 xff0
  • python装饰器详解(四)---把参数传递给装饰器

    因为装饰器必须接收一个函数当做参数 所以 不可以直接把被装饰函数的参数传递给装饰器 装饰器就是一个普通的函数 xff0c 回顾 def my decorator func print 34 I am an ordinary function
  • Motion Deblurring图像运动去模糊代码

    http www di ens fr whyte Efficient Deblurring for Shaken and Partially Saturated Images http www di ens fr willow resear
  • maven执行install时报错 The packaging for this project did not assign a file to the build artifact

    问题描述 maven中执行plugins下面的install install时会报如下错误 span class token class name Failed span span class token keyword to span s
  • realsense相机两种获取相机内外参的方式

    https www it610 com article 1296417297711308800 htm 命令 xff1a rs sensor control 这个命令是一个exe文件 xff0c 可以去 C Program Files x8
  • wget设置代理

    1 在bash shell中设定代理 basrhc export http proxy 61 34 166 111 53A 167 3128 34 export ftp proxy 61 34 166 111 53A 167 3128 34
  • chown,chgrp,chmod,u+s,g+s,o+t

    chown user file directory change owner 将后面的目标文件或者目录的所有者替换成 user chgrp group file directory change group 将目标文件或者目录的所有组替换成
  • Segment Routing笔记(一)

    SR 理论 一 MPLS TE缺点 RSVP TE大部分都是为了FRR的目的不支持ECMP所有流量都需要在隧道里诞生了 战术型 TE xff0c 只在需要的时候使用 术语 TI LFA 与拓扑无关的无环路备份 xff0c 能保证备份路径的最
  • Springboot+Netty搭建UDP服务端

    UDP是一个无连接协议 xff0c 应用范围很大 xff0c 对于一些低功耗的设备可以使用UDP方式向云端推送消息信息 xff0c 也可以在推送消息时收到从云端原路返回的消息 xff0c 使用Netty 43 SpringBoot方式可以快