import java.net.*; import java.io.*; public class Monitor { // Can listen & send on the same socket: private DatagramSocket s; private InetAddress hostAddress; private byte[] buf = new byte[256]; private DatagramPacket dp = new DatagramPacket(buf, buf.length); private int id, port; public Monitor(String port_s, String serverName) { try { // Auto-assign port number: s = new DatagramSocket(); hostAddress = InetAddress.getByName(serverName); port = Integer.parseInt(port_s); } catch(UnknownHostException e) { System.err.println("Cannot find host"); System.exit(1); } catch(SocketException e) { System.err.println("Can't open socket"); e.printStackTrace(); System.exit(1); } System.out.println("Monitor starting"); } public void sendData() { String outMessage = "n"; // Make and send a datagram: byte[] sendData = outMessage.getBytes(); DatagramPacket request = new DatagramPacket(sendData, sendData.length, hostAddress, port); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); try { while (true) { in.readLine(); s.send(request); // Block until it reply is back: s.receive(dp); // Print out the reply: String rcvd = new String(dp.getData(), 0, dp.getLength()); System.out.println(rcvd); } } catch(IOException e) { e.printStackTrace(); System.exit(1); } } public static void main(String[] args) { new Monitor(args[0], args[1]).sendData(); } }