在Spring官网https://start.spring.io/
创建Spring Boot项目,添加spring-boot-starter-webflux
及lombok
依赖。
<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>
在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));
}
}
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
}
}
UDP
数据解析完成后等操作的handler
,UdpHandler
上一个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);
}
}
UDP Client
进行数据封装的handler
,UdpEncoderHandler
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());
}
}
使用socketTool
进行测试,创建UDP Client
,输入UDP Server
的IP
及端口
,本地UDP Client
的端口,向UDP Server
发送hello world,I'm client
,UDP Server
向客户端返回hello world