How to implement UDP server to read input from client in Spring Boot

Viewed 2391

I have implemented a web app with spring boot(version 1.5.3) framework. Now I need a udp server that receive incoming message from client. How can I add this functionality into my spring boot based project?

I followed How to implement UDP in Spring framework link for reference but could not get w.r.t spring boot

Can anyone help me in understanding this please

Thanks Maruthy

1 Answers

Have a dependency on spring boot integration and spring-ip.

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-integration</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.integration</groupId>
        <artifactId>spring-integration-ip</artifactId>
        <version>5.1.0.RELEASE</version>
    </dependency>

Then create simple "IntegrationFlow" with "UnicastReceivingChannelAdapter" and to associate that, create a bean for receiving UDP messages

@Bean
  public IntegrationFlow processUniCastUdpMessage() {
    return IntegrationFlows
      .from(new UnicastReceivingChannelAdapter(11111))
      .handle("UDPServer", "handleMessage")
      .get();
  }

@Service
public class UDPServer
{
  public void handleMessage(Message message)
  {
    String data = new String((byte[]) message.getPayload());
    System.out.print(data);
  }
}

Also using simple client using "UnicastSendingMessageHandler" can send the message to UDP server.

UnicastSendingMessageHandler handler =
      new UnicastSendingMessageHandler("localhost", 11111);

String payload = "Hello world";
handler.handleMessage(MessageBuilder.withPayload(payload).build());
Related