基于Spring BOOT + Spring Webflux的UDP数据接收及发送

UDP协议全称是用户数据报协议,在网络中它与TCP协议一样用于处理数据包,是一种无连接的协议。

1.创建Spring BOOT项目

在Spring官网https://start.spring.io/创建Spring Boot项目,添加spring-boot-starter-webfluxlombok依赖。

基于Spring BOOT + Spring Webflux的UDP数据接收及发送_第1张图片


<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0modelVersion>
	<parent>
		<groupId>org.springframework.bootgroupId>
		<artifactId>spring-boot-starter-parentartifactId>
		<version>2.1.3.RELEASEversion>
		<relativePath/> 
	parent>
	<groupId>com.examplegroupId>
	<artifactId>demoartifactId>
	<version>0.0.1-SNAPSHOTversion>
	<name>demoname>
	<description>Demo project for Spring Bootdescription>

	<properties>
		<java.version>1.8java.version>
	properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.bootgroupId>
			<artifactId>spring-boot-starterartifactId>
		dependency>

		<dependency>
			<groupId>org.springframework.bootgroupId>
			<artifactId>spring-boot-starter-testartifactId>
			<scope>testscope>
		dependency>
		<dependency>
			<groupId>org.projectlombokgroupId>
			<artifactId>lombokartifactId>
		dependency>

		<dependency>
			<groupId>org.springframework.bootgroupId>
			<artifactId>spring-boot-starter-webfluxartifactId>
		dependency>
	dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.bootgroupId>
				<artifactId>spring-boot-maven-pluginartifactId>
			plugin>
		plugins>
	build>

project>

2.创建UDP Server

在Spring BOOT启动类中添加UDP Server,CommandLineRunner是Spring BOOT项目启动时会执行的任务,及在Spring BOOT启动时创建UDP Server

package com.example.demo;

import com.example.demo.handler.UdpDecoderHandler;
import com.example.demo.handler.UdpEncoderHandler;
import com.example.demo.handler.UdpHandler;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import reactor.core.publisher.Flux;
import reactor.netty.udp.UdpServer;

import java.time.Duration;

@SpringBootApplication
public class DemoApplication {
	public static void main(String[] args) {
		SpringApplication.run(DemoApplication.class, args);
	}
	@Bean
	CommandLineRunner serverRunner(UdpDecoderHandler udpDecoderHanlder, UdpEncoderHandler udpEncoderHandler, UdpHandler udpHandler) {
		return strings -> {
			createUdpServer(udpDecoderHanlder, udpEncoderHandler, udpHandler);
		};
	}

	/**
	 *
	 * 创建UDP Server
	 * @param udpDecoderHandler: 用于解析UDP Client上报数据的handler
	 * @param udpEncoderHandler: 用于向UDP Client发送数据进行编码的handler
	 * @param udpHandler: 用户维护UDP链接的handler
	 */
	private void createUdpServer(UdpDecoderHandler udpDecoderHandler, UdpEncoderHandler udpEncoderHandler, UdpHandler udpHandler) {
		UdpServer.create()
				.handle((in,out) -> {
					in.receive()
							.asByteArray()
							.subscribe();
					return Flux.never();
				})
				.port(8888) //UDP Server端口
				.doOnBound(conn -> conn
						.addHandler("decoder",udpDecoderHandler)
						.addHandler("encoder", udpEncoderHandler)
						.addHandler("handler", udpHandler)
						) //可以添加多个handler
				.bindNow(Duration.ofSeconds(30));
	}
}

3.解析UDP Client数据上报的handler,UdpDecoderHandler

UdpDecoderHandler继承MessageToMessageDecoder,将UDP Client上报的进行decoder解析,UDP Client上报的数据类型为DatagramPacket

package com.example.demo.handler;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.socket.DatagramPacket;
import io.netty.handler.codec.MessageToMessageDecoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UdpDecoderHandler extends MessageToMessageDecoder<DatagramPacket>  {
    private static final Logger LOGGER = LoggerFactory.getLogger(UdpDecoderHandler.class);

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, DatagramPacket datagramPacket, List<Object> out) throws Exception {
        ByteBuf byteBuf = datagramPacket.content();
        byte[] data = new byte[byteBuf.readableBytes()];
        byteBuf.readBytes(data);
        String msg = new String(data);
        LOGGER.info("{}收到消息{}:" + msg);
        out.add(msg); //将数据传入下一个handler
    }
}

4.维护UDP数据解析完成后等操作的handlerUdpHandler

上一个decoder handler数据解析完成后,将数据传入UdpHandler,我们将消息分类,交由不同的service去做相应的处理,这里就不做具体处理了

package com.example.demo.handler;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;


@Slf4j
@Service
public class UdpHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        String preHandlerAfferentMsg = (String)msg; //得到消息后,可根据消息类型分发给不同的service去处理数据
        log.info("{}preHandler传入的数据{}"+preHandlerAfferentMsg);
        ctx.writeAndFlush("hello word"); //返回数据给UDP Client
        log.info("channelRead");
    }

    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        log.info("channelRegistered");
        ctx.fireChannelRegistered();
    }

    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
        log.info("channelUnregistered");
        ctx.fireChannelUnregistered();
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("channelActive");
        ctx.fireChannelActive();
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        log.info("channelInactive");
        ctx.fireChannelInactive();
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        log.info("channelReadComplete");
        ctx.fireChannelReadComplete();
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        log.info("userEventTriggered");
        ctx.fireUserEventTriggered(evt);
    }

    @Override
    public void channelWritabilityChanged(ChannelHandlerContext ctx) throws Exception {
        log.info("channelWritabilityChanged");
        ctx.fireChannelWritabilityChanged();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
            throws Exception {
        log.info("exceptionCaught");
        ctx.fireExceptionCaught(cause);
    }
}

5.将需要发送给UDP Client进行数据封装的handlerUdpEncoderHandler

ctx.writeAndFlush("hello word")会调用UdpEncoderHandler,将数据进行decoder封装成DatagramPacket类型,发送给UDP Client

package com.example.demo.handler;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.socket.DatagramPacket;
import io.netty.handler.codec.MessageToMessageEncoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.net.InetSocketAddress;
import java.util.List;

@Service
public class UdpEncoderHandler extends MessageToMessageEncoder {

    private static final Logger LOGGER = LoggerFactory.getLogger(UdpEncoderHandler.class);

    @Override
    protected void encode(ChannelHandlerContext ctx, Object o, List list) throws Exception {
        byte[] data = o.toString().getBytes();
        ByteBuf buf = ctx.alloc().buffer(data.length);
        buf.writeBytes(data);
        InetSocketAddress inetSocketAddress = new InetSocketAddress("127.0.0.1", 1111);//指定客户端的IP及端口
        list.add(new DatagramPacket(buf, inetSocketAddress));
        LOGGER.info("{}发送消息{}:" + o.toString());
    }
}

6.测试

使用socketTool进行测试,创建UDP Client,输入UDP ServerIP端口,本地UDP Client的端口,向UDP Server发送hello world,I'm clientUDP Server向客户端返回hello world
基于Spring BOOT + Spring Webflux的UDP数据接收及发送_第2张图片
基于Spring BOOT + Spring Webflux的UDP数据接收及发送_第3张图片

你可能感兴趣的:(spring,netty,UDP)