Java examples for Network:Datagram Channel
DatagramChannel time server, Provide RFC 868 time service (http://www.ietf.org/rfc/rfc0868.txt)
import java.net.InetSocketAddress; import java.net.SocketAddress; import java.net.SocketException; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.channels.DatagramChannel; public class Main { private static final int DEFAULT_TIME_PORT = 9999; private static final long DIFF_1900 = 2208988800L; protected DatagramChannel channel; public Main() throws Exception { this.channel = DatagramChannel.open(); this.channel.socket().bind(new InetSocketAddress(DEFAULT_TIME_PORT)); System.out.println("Listening on port " + DEFAULT_TIME_PORT+ " for time requests"); }// w ww.j a v a2s. com public void listen() throws Exception { ByteBuffer longBuffer = ByteBuffer.allocate(8); longBuffer.order(ByteOrder.BIG_ENDIAN); longBuffer.putLong(0, 0); longBuffer.position(4); ByteBuffer buffer = longBuffer.slice(); while (true) { buffer.clear(); SocketAddress sa = this.channel.receive(buffer); if (sa == null) { continue; } System.out.println("Time request from " + sa); buffer.clear(); longBuffer.putLong(0, (System.currentTimeMillis() / 1000) + DIFF_1900); this.channel.send(buffer, sa); } } public static void main(String[] argv) throws Exception { try { Main server = new Main(); server.listen(); } catch (SocketException e) { e.printStackTrace(); } } }