// // example of use of java.net.* classes: send/receive messages using // UDP (Datagram* classes). // this program is the server; UDPclient.java is the client. // // adapted from example in ch. 11 of _Exploring Java_, Niemeyer & Peck. // import java.net.* ; import java.io.* ; // // ---- main ----------------------------------------------------------- // // command-line argument is port number. // // program receives and prints messages sent by UDPclient program // (called one or more times, possibly from different machines). // // instructions for testing: // // (1) start this program: // java UDPserver nnnn // (nnnn is any port number you choose, higher than 1024) // suppose mymachine.org is the name of the machine on which // you've done this, and nnnn = 1234. // // (2) run UDPclient one or more times: // java UDPclient mymachine.org 1234 // // you can do this on the same machine (in a different window // usually) or on a different machine. // // if you don't know the name of the machine on which you're // running, you can use its IP address instead. for // a Windows machine, you can (at least on the CIRCA // machines) get its IP address by typing "winipcfg" // at a DOS prompt. // // when done, stop the server with control-C. // // these instructions have been tested on the CISE Unix machines and // the CIRCA Windows machines. // class UDPserver { static final int PKSIZE = 1024 ; public static void main(String[] args) throws IOException { if (args.length < 1) { System.out.println("Argument is portnum") ; System.exit(-1) ; } // make a "listener" socket (specify port number). DatagramSocket s = new DatagramSocket(Integer.parseInt(args[0])) ; while (true) { // prepare packet object to receive message. DatagramPacket packet = new DatagramPacket( new byte [PKSIZE], PKSIZE) ; // receive message. s.receive(packet) ; // extract data (message text sent by client). // ("trim" added to cope with JDK 1.1.3 // bug (?) that added blanks to packet // data.) String msg = new String(packet.getData()).trim() ; // print message text and sender's hostname. System.out.println("Message from UDPclient at " + packet.getAddress().getHostName() + ": " + msg) ; } } }