import java.io.IOException; import java.net.InetSocketAddress; import java.net.StandardSocketOptions; import java.nio.ByteBuffer; import java.nio.channels.DatagramChannel; import java.util.logging.Level; /** * Created by leonid on 08.07.14. */ public class UDPListenerTest { private volatile DatagramChannel channel; private ListenerThread listenerThread; UDPListenerTest() { try { channel = DatagramChannel.open(); // The following receive buffer value is empirical. It's known to // be enough to handle 1000 clients sending JUT records every 1-10s channel.setOption(StandardSocketOptions.SO_RCVBUF, 6553600); channel.bind(new InetSocketAddress(19870)); listenerThread = new ListenerThread(); listenerThread.start(); } catch (Exception z) { z.printStackTrace(); } } public void shutdown() { listenerThread.terminate(); try { listenerThread.join(); } catch (Exception z) { z.printStackTrace(System.err); } } public static void main(String[] args) { UDPListenerTest t = new UDPListenerTest(); try { Thread.sleep(3000); } catch (Exception e) { } t.shutdown(); } public class ListenerThread extends Thread { private volatile boolean shouldTerminate; @Override public void run() { ByteBuffer buf = ByteBuffer.allocate(6553600); shouldTerminate = false; while (!shouldTerminate) { try { buf.rewind(); channel.receive(buf); } catch (IOException z) { if (!shouldTerminate) { z.printStackTrace(System.err); } } } } public void terminate() { shouldTerminate = true; try { channel.close(); } catch (Exception z) { z.printStackTrace(System.err); // ignore } } } }