UDP協議全稱是用戶數據報協議,在網絡中它與TCP協議一樣用於處理數據包,是一種無連接的協議。
1.創建Spring BOOT項目
在Spring官網https://start.spring.io/創建Spring Boot項目,添加spring-boot-starter-webflux及lombok依賴。
<?xml version="1.0" encoding="UTF-8"?>
<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.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
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));
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
3.解析UDP Client數據上報的handler,UdpDecoderHandler
UdpDecoderHandler繼承MessageToMessageDecoder<DatagramPacket>,將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
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
4.維護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);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
5.將需要發送給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());
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
6.測試
使用socketTool進行測試,創建UDP Client,輸入UDP Server的IP及端口,本地UDP Client的端口,向UDP Server發送hello world,I'm client,UDP Server向客戶端返回hello world