SpringBoot 开启 UDP 服务发送及接收 UDP 协议信息

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("发送成功");
    }
 
}
复制代码

 

 
复制代码

 

posted @   Booom丶  阅读(2419)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示