How to implement UDP as part of Spring

I implemented a web application with the spring framework. Now I need an udp server that accepts incoming messages from clients (Android devices). How to add this functionality to my spring project? Thank.

+1
source share
1 answer

If you want to use TCP and UDP Support Spring Integration , provided that you just get a UDP message and do something with this message, you must follow these steps:

Create message consumer

package com.example.udp;

import org.springframework.messaging.Message;

public class UDPConsumer {

    @Autowire what you want, this will be a Spring Bean

    @ServiceActivator
    public void consume(Message message) {
         ... do something with message ...
    }
}

Optional: create udp-server.properties with some property

udp-server.threads=10
udp-server.port=4000
udp-server.buffer-size=500
...

Create a configuration file

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:int="http://www.springframework.org/schema/integration"
    xmlns:int-ip="http://www.springframework.org/schema/integration/ip"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/integration http://www.springframework.org/schema/integration/spring-integration.xsd
        http://www.springframework.org/schema/integration/ip http://www.springframework.org/schema/integration/ip/spring-integration-ip.xsd">

    <context:property-placeholder location="classpath:udp-server.properties" />

    <bean id="udpConsumer" class="com.example.udp.UDPConsumer" />

    <int:channel id="inputChannel">
        <int:queue />
    </int:channel>

    <int-ip:udp-inbound-channel-adapter id="udpReceiver"
        channel="inputChannel"
        port="${udp-server.port}"
        pool-size="${udp-server.threads}"
        receive-buffer-size="${udp-server.buffer-size}"
        multicast="false"
        check-length="true"/>

    <int:service-activator input-channel="inputChannel"
        ref="udpConsumer" />

    <int:poller default="true" fixed-rate="500" />

</beans>

: Spring , . .

+5

Source: https://habr.com/ru/post/1680811/


All Articles