import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.util.Scanner; public class EchoClient { public static void main(String[] args) throws Exception { if( args.length != 2 ) { System.out.println("usage: java EchoClient hostname port"); System.exit(0); } // Prepare address and port of the server String server = args[0] ; int port = Integer.parseInt( args[1] ); InetAddress srvAddress = InetAddress.getByName( server ); String request; // Create a helper scanner to read complete lines from standard input try(Scanner in = new Scanner( System.in )) { // Read the "request" from the standard input System.out.print("Say what? " ); request = in.nextLine(); } // Prepare the socket to exchange datagrams try( DatagramSocket socket = new DatagramSocket() ) { // Convert the request string into bytes byte[] reqData = request.getBytes(); // Prepare the datagram filling in the contents and address in one go DatagramPacket echoReq = new DatagramPacket( reqData, reqData.length, srvAddress, port ); socket.send( echoReq ); // Prepare an empty datagram to receive the reply byte[] buffer = new byte[65536] ; DatagramPacket echoReply = new DatagramPacket( buffer, buffer.length ); socket.receive( echoReply ); // Create a string from the contents of the datagram String echoedMsg = new String( echoReply.getData(), 0, echoReply.getLength() ) ; System.out.printf("Got echo: \"%s\"\n", echoedMsg ) ; } } }