I made a simple Spring Boot project to listen for UDP transmissions and save the results. For the purposes of this question I will just have the handler print out the input.
Here is the configuration bean:
package com.wheresjim.udp.config
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.integration.dsl.IntegrationFlow
import org.springframework.integration.ip.udp.UnicastReceivingChannelAdapter
@Configuration
class UdpConfig {
private Integer port = 6767
@Bean
IntegrationFlow processUdpMessage() {
IntegrationFlow
.from(new UnicastReceivingChannelAdapter(port))
.handle("udpService", "receive")
.get()
}
}
Here's the handler:
package com.wheresjim.udp.service
import org.springframework.messaging.Message
import org.springframework.stereotype.Component;
@Component
class UdpService {
void receive(Message message) {
String data = new String((byte[]) message.getPayload())
System.out.print(data)
}
}
Here's the client:
DatagramSocket socket = new DatagramSocket()
InetAddress address = InetAddress.getByName('localhost')
String sendUDP(String msg, address, socket) {
byte[] buf = msg.getBytes()
println msg.getBytes().length
DatagramPacket packet = new DatagramPacket(buf, buf.length, address, 6767)
socket.send(packet)
packet = new DatagramPacket(buf, buf.length)
socket.receive(packet)
String received = new String(packet.getData(), 0, packet.getLength())
return received
}
String testMsg = '<?xml version="1.0" encoding="UTF-8"?><TestMsg><Text>Hello World</Text></TestMsg>''
try {
sendUDP(testMsg, address, socket)
} catch (Exception e) {
e.printStackTrace()
} finally {
socket.close()
}
When I send a message, it is received and displayed correctly. However there is not an acknowledgment or reply sent to the client. As such the client just hangs and I have to restart to send another message. How can I get this to send a simple reply to allow multiple messages to be sent?
Please note, the language used is Groovy
Thanks to the help from Artem and Gary, I was able to put together a simple solution. I added a method to my UDPService that ACKs the incoming message, and I call it when I am finished processing the input:
void ackUdp(Message message) {
String ackMessage = ''
DatagramPacket ackPacket = new DatagramPacket(
ackMessage.getBytes(),
ackMessage.length(),
InetAddress.getByName(message.getHeaders().get('ip_address')),
message.getHeaders().get('ip_port')
)
DatagramSocket socket = new DatagramSocket()
try {
socket.send(ackPacket)
} catch (Exception e) {
e.printStackTrace()
} finally {
socket.close()
}
}