SpringBoot 開啟 UDP 服務傳送及接收 UDP 協議資訊
阿新 • • 發佈:2022-05-11
SpringBoot 開啟 UDP 服務,進行接收 UDP,及傳送 UDP,這裡依賴的是 SpringBoot 內建 integration 包
1. Config
新增 Jar,下面用的是 SpringBoot 內建 integration 依賴
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-integration</artifactId> <exclusions> <exclusion> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-logging</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.springframework.integration</groupId> <artifactId>spring-integration-ip</artifactId> </dependency>
2. Receiving
/** * UDP訊息接收服務*/ @Configuration public class UdpServer { private static final Logger logger = LoggerFactory.getLogger(UdpServer.class); @Value("${udp.port}") private Integer udpPort;/** * UDP訊息接收服務寫法一 * https://docs.spring.io/spring-integration/reference/html/ip.html#inbound-udp-adapters-java-configuration * * @param * @return org.springframework.integration.ip.udp.UnicastReceivingChannelAdapter*/ /*@Bean public UnicastReceivingChannelAdapter unicastReceivingChannelAdapter() { // 例項化一個UDP訊息接收服務 UnicastReceivingChannelAdapter unicastReceivingChannelAdapter = new UnicastReceivingChannelAdapter(udpPort); // unicastReceivingChannelAdapter.setOutputChannel(new DirectChannel()); unicastReceivingChannelAdapter.setOutputChannelName("udpChannel"); logger.info("UDP服務啟動成功,埠號為: {}", udpPort); return unicastReceivingChannelAdapter; }*/ /** * UDP訊息接收服務寫法二 * https://docs.spring.io/spring-integration/reference/html/ip.html#inbound-udp-adapters-java-dsl-configuration * * @param * @return org.springframework.integration.dsl.IntegrationFlow*/ @Bean public IntegrationFlow integrationFlow() { logger.info("UDP服務啟動成功,埠號為: {}", udpPort); return IntegrationFlows.from(Udp.inboundAdapter(udpPort)).channel("udpChannel").get(); } /** * 轉換器 * * @param payload * @param headers * @return java.lang.String*/ @Transformer(inputChannel = "udpChannel", outputChannel = "udpFilter") public String transformer(@Payload byte[] payload, @Headers Map<String, Object> headers) { String message = new String(payload); // 轉換為大寫 // message = message.toUpperCase(); // 向客戶端響應,還不知道怎麼寫 return message; } /** * 過濾器*/ @Filter(inputChannel = "udpFilter", outputChannel = "udpRouter") public boolean filter(String message, @Headers Map<String, Object> headers) { // 獲取來源Id String id = headers.get("id").toString(); // 獲取來源IP,可以進行IP過濾 String ip = headers.get("ip_address").toString(); // 獲取來源Port String port = headers.get("ip_port").toString(); // 資訊資料過濾 /*if (message.indexOf("-") < 0) { // 沒有-的資料會被過濾 return false; }*/ return true; } /** * 路由分發處理器*/ @Router(inputChannel = "udpRouter") public String router(String message, @Headers Map<String, Object> headers) { // 獲取來源Id String id = headers.get("id").toString(); // 獲取來源IP,可以進行IP過濾 String ip = headers.get("ip_address").toString(); // 獲取來源Port String port = headers.get("ip_port").toString(); // 篩選,走那個處理器 if (false) { return "udpHandle2"; } return "udpHandle1"; } /** * 最終處理器1*/ @ServiceActivator(inputChannel = "udpHandle1") public void udpMessageHandle(String message) throws Exception { // 可以進行非同步處理 businessService.udpHandleMethod(message); logger.info("UDP1:" + message); } /** * 最終處理器2*/ @ServiceActivator(inputChannel = "udpHandle2") public void udpMessageHandle2(String message) throws Exception { logger.info("UDP2:" + message); } }
3. Sending
3.1. UdpSimpleClient
/** * 預設傳送方式*/ @Service public class UdpSimpleClient { private final static Logger logger = LoggerFactory.getLogger(UdpSimpleClient.class); @Value("${udp.port}") private Integer udpPort; public void sendMessage(String message) { logger.info("傳送UDP: {}", message); InetSocketAddress inetSocketAddress = new InetSocketAddress("localhost", udpPort); byte[] udpMessage = message.getBytes(); DatagramPacket datagramPacket = null; try (DatagramSocket datagramSocket = new DatagramSocket()) { datagramPacket = new DatagramPacket(udpMessage, udpMessage.length, inetSocketAddress); datagramSocket.send(datagramPacket); } catch (IOException e) { logger.error(e.getMessage(), e); } logger.info("傳送成功"); } }
3.2. UdpIntegrationClient
/** * IntegrationClientConfig*/ @Configuration public class UdpIntegrationClientConfig { @Value("${udp.port}") private Integer udpPort; @Bean @ServiceActivator(inputChannel = "udpOut") public UnicastSendingMessageHandler unicastSendingMessageHandler() { UnicastSendingMessageHandler unicastSendingMessageHandler = new UnicastSendingMessageHandler("localhost", udpPort); return unicastSendingMessageHandler; } }
/** * Integration傳送方式*/ @Service public class UdpIntegrationClient { private final static Logger logger = LoggerFactory.getLogger(UdpIntegrationClient.class); @Autowired private UnicastSendingMessageHandler unicastSendingMessageHandler; public void sendMessage(String message) { logger.info("傳送UDP: {}", message); unicastSendingMessageHandler.handleMessage(MessageBuilder.withPayload(message).build()); logger.info("傳送成功"); } }