Java examples for Network:Datagram Channel
Time-service client using DatagramChannel
import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.channels.DatagramChannel; import java.util.Iterator; import java.util.LinkedList; import java.util.List; public class Main { protected int port = 9999; protected List remoteHosts; protected DatagramChannel channel; public Main() throws Exception { this.channel = DatagramChannel.open(); }//w ww . j a va 2 s . c om protected InetSocketAddress receivePacket(DatagramChannel channel, ByteBuffer buffer) throws Exception { buffer.clear(); return ((InetSocketAddress) channel.receive(buffer)); } protected void sendRequests() throws Exception { ByteBuffer buffer = ByteBuffer.allocate(1); Iterator it = remoteHosts.iterator(); while (it.hasNext()) { InetSocketAddress sa = (InetSocketAddress) it.next(); buffer.clear().flip(); channel.send(buffer, sa); } } public void getReplies() throws Exception { ByteBuffer longBuffer = ByteBuffer.allocate(8); longBuffer.order(ByteOrder.BIG_ENDIAN); longBuffer.putLong(0, 0); longBuffer.position(4); ByteBuffer buffer = longBuffer.slice(); int expect = remoteHosts.size(); int replies = 0; System.out.println("Waiting for replies..."); while (true) { InetSocketAddress sa; sa = receivePacket(channel, buffer); buffer.flip(); replies++; printTime(longBuffer.getLong(0), sa); if (replies == expect) { System.out.println("All packets answered"); break; } System.out.println("Received " + replies + " of " + expect + " replies"); } } protected void printTime(long remote1900, InetSocketAddress sa) { System.out.println("Reply from " + sa.getHostName() + ":" + sa.getPort()); } protected void parseArgs(String[] argv) { remoteHosts = new LinkedList(); InetSocketAddress sa = new InetSocketAddress("127.0.0.1", port); remoteHosts.add(sa); } public static void main(String[] argv) throws Exception { Main client = new Main(); client.sendRequests(); client.getReplies(); } }