You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Spring Integration DSL接收远程UDP服务器消息

使用Spring Integration DSL实现UDP数据包接收

1. 添加依赖

如果使用Maven,在pom.xml中添加Spring Integration UDP模块依赖:

<dependency>
    <groupId>org.springframework.integration</groupId>
    <artifactId>spring-integration-ip</artifactId>
    <version>你的Spring Integration版本</version>
</dependency>

版本建议与你的Spring Boot/Spring框架版本匹配

2. 编写Spring Integration DSL配置类

创建配置类,通过DSL定义UDP入站接收流程:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.annotation.EnableIntegration;
import org.springframework.integration.dsl.IntegrationFlow;
import org.springframework.integration.dsl.IntegrationFlows;
import org.springframework.integration.ip.dsl.Udp;

@Configuration
@EnableIntegration
public class UdpReceiverConfig {

    // 监听的本地端口,需与远程服务器发送的目标端口一致
    private static final int LISTEN_PORT = 你的端口号;

    @Bean
    public IntegrationFlow udpInboundFlow() {
        return IntegrationFlows.from(
                // 配置UDP入站适配器,监听指定端口
                Udp.inboundAdapter(LISTEN_PORT)
                        // 可选:如果需要限制仅接收特定IP的数据包,可添加过滤器
                        // .filter(message -> message.getHeaders().get("ip_address").equals("远程服务器IP"))
        )
        .handle((payload, headers) -> {
            // 处理接收到的UDP数据包
            // payload默认是字节数组,可转成字符串
            String receivedData = new String((byte[]) payload);
            System.out.println("接收到UDP数据包: " + receivedData);
            System.out.println("发送方IP: " + headers.get("ip_address"));
            return null;
        })
        .get();
    }
}

3. 关键说明

  • Udp.inboundAdapter(LISTEN_PORT):创建UDP入站适配器,监听指定的本地端口,远程服务器发送的UDP数据包目标端口需与此一致。
  • 消息payload默认是byte[]类型,可根据实际需求转换为字符串或其他格式。
  • 消息头ip_address包含发送方的IP地址,可用于验证来源或做后续处理。
  • 如果需要对接收的数据包做更复杂的处理,可替换handle方法中的逻辑,比如转发到其他通道、存储到数据库等。

4. 启动应用测试

启动Spring应用后,远程服务器向你的应用所在机器的指定端口发送UDP数据包,即可在控制台看到接收到的内容。

内容的提问来源于stack exchange,提问作者Mark Philips

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 02:56:01