// // example of use of java.net.* classes: send/receive messages using // UDP (Datagram* classes). // this program is the client; UDPserver.java is the server. // // adapted from example in ch. 11 of _Exploring Java_, Niemeyer & Peck. // import java.net.* ; import java.io.* ; // // a UDPclient object can be used to send messages using UDP to a // corresponding UDPserver (see UDPserver.java). // class UDPclient { String theHost ; int thePort ; UDPclient(String h, int p) { theHost = h ; thePort = p ; } // sends a packet containing "message" to the server. private void sendMessage(String message) { try { byte[] data = message.getBytes() ; // get IP address for hostname. InetAddress addr = InetAddress.getByName(theHost) ; // build packet to send, including // message text and destination info. DatagramPacket packet = new DatagramPacket(data, data.length, addr, thePort) ; // create "sender" socket (no host or port, // since that's in the messages). DatagramSocket sock = new DatagramSocket() ; // send the message. sock.send(packet) ; sock.close() ; } catch (IOException e) { System.out.println(e) ; } } // // ---- main --------------------------------------------------- // // command-line arguments are hostname, port for server. // hostname is the name (or IP address) of the machine // on which UDPserver is executing. port is the port // on which it was started. // // program sends "hello" and "goodbye" messages to server. // note that since this is UDP, the program executes // successfully even if no server program is running. // compare to programs using TCP. // public static void main(String[] args) { if (args.length < 2) { System.out.println("Arguments are hostname, " + "portnum") ; System.exit(-1) ; } UDPclient c = new UDPclient(args[0], Integer.parseInt(args[1])) ; c.sendMessage("Hello!") ; c.sendMessage("Goodbye!") ; } }