-
-
Save ennerf/0ddc4396d15852d28e4eca4a8a923eb7 to your computer and use it in GitHub Desktop.
UDP Java server (incomplete example for a blog post)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class UdpBenchmarkServer implements Runnable { | |
public static void main(String[] args) throws Exception { | |
// Start service | |
UdpBenchmarkServer server = new UdpBenchmarkServer(SERVER_PORT); | |
Thread thread = new Thread(server); | |
thread.setDaemon(true); | |
thread.start(); | |
// Periodically persist buffered data to disk | |
FileChannel fileChannel = new FileOutputStream("output.bin").getChannel(); | |
while (true) { | |
server.log.writeTo(fileChannel); | |
Silencer.sleepMillis(1000); | |
} | |
} | |
public UdpBenchmarkServer(int port) throws IOException { | |
// Setup channel | |
channel = DatagramChannel.open(StandardProtocolFamily.INET); | |
channel.setOption(StandardSocketOptions.SO_RCVBUF, DEFAULT_BUFFER_SIZE); | |
channel.setOption(StandardSocketOptions.SO_SNDBUF, DEFAULT_BUFFER_SIZE); | |
channel.setOption(StandardSocketOptions.SO_BROADCAST, true); | |
channel.configureBlocking(true); | |
// Bind to local port | |
final InetAddress ANY_IP = null; | |
channel.bind(new InetSocketAddress(ANY_IP, port)); | |
} | |
@Override | |
public void run() { | |
Thread.currentThread().setPriority(Thread.MAX_PRIORITY - 1); | |
final ByteBuffer rxBuffer = ByteBuffer.allocateDirect(DEFAULT_BUFFER_SIZE); | |
rxBuffer.order(ByteOrder.LITTLE_ENDIAN); | |
while (true) { | |
try { | |
// Receive timings via UDP message | |
InetSocketAddress source = (InetSocketAddress) channel.receive(rxBuffer); | |
// Add local meta data | |
rxBuffer.putLong(System.nanoTime()); | |
rxBuffer.putLong(System.currentTimeMillis()); | |
rxBuffer.putLong(coerceToLong(source)); | |
// Add received data to buffer to be persistet (wait-free) | |
rxBuffer.flip(); | |
log.put(rxBuffer); | |
rxBuffer.clear(); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
} | |
} | |
final DatagramChannel channel; | |
final int DEFAULT_BUFFER_SIZE = 16 * 1024; // 16 KB | |
final SingleWriterLog log = new SingleWriterLog(DEFAULT_BUFFER_SIZE * 1024); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment