Tacitus86 Tacitus86 - 1 month ago 20
Java Question

OnMessage() functionality for UDP

I was wondering if there is a type of OnMessage() type functionality for UDP messages using DatagramPacket? I want to be able to ensure that I get all messages when they come across so I don't waste resources randomly grabbing on a timer.

The OnMessage I am referring to the one done in WebSocketClient. Or some functionality similar to "Available" in .net.

While (rxUdpClient.Available > 0)


I am monitoring several ports so a thread is called which will do a run() for each port. Problem is I seem to have messages coming in at a massive rate 40+/sec.

This is what I currently have:

public void run()
{
DatagramSocket sock = null;
sock = new DatagramSocket(port);
byte[] buffer = new byte[DataAdapterFB1.HEADER_SIZE + DataAdapterFB1.MAX_DATA_BYTES];
DatagramPacket incoming = new DatagramPacket(buffer, buffer.length);

while (true){
sock.receive(incoming);
byte[] data = incoming.getData();
String s = new String(data, 0, incoming.getLength());
//This is the processing code, but it isn't its own thread...
ScadaMsg newMessage = new ScadaMsg(data);
}
}

Answer

DatagramPacket receive() operation is blocking, so what you will normally do is just launch a separate thread, which will listen for the incoming datagrams in a loop and dispatch them for further processing, like that:

void run() {
    socket = new DatagramSocket(4445);

    while(true) {
         byte[] buf = new byte[256];
         DatagramPacket packet = new DatagramPacket(buf, buf.length);
         socket.receive(packet); //JVM will wait here, until there is an incoming packet
         onMessage(packet.getData())
    }
 } 

 public abstract void onMessage(final byte[] pkt);