Java Reference
In-Depth Information
Example 5•11: UDPSend.java (continued)
// Parse the arguments
String host = args[0];
int port = Integer.parseInt(args[1]);
// Figure out the message to send.
// If the third argument is -f, then send the contents of the file
// specified as the fourth argument. Otherwise, concatenate the
// third and all remaining arguments and send that.
byte[] message;
if (args[2].equals("-f")) {
File f = new File(args[3]);
int len = (int)f.length(); // figure out how big the file is
message = new byte[len]; // create a buffer big enough
FileInputStream in = new FileInputStream(f);
int bytes_read = 0, n;
do { // loop until we've read it all
n = in.read(message, bytes_read, len-bytes_read);
bytes_read += n;
} while((bytes_read < len) && (n != -1));
}
else { // Otherwise, just combine all the remaining arguments.
String msg = args[2];
for (int i = 3; i < args.length; i++) msg += " " + args[i];
message = msg.getBytes();
}
// Get the internet address of the specified host
InetAddress address = InetAddress.getByName(host);
// Initialize a datagram packet with data and address
DatagramPacket packet = new DatagramPacket(message, message.length,
address, port);
// Create a datagram socket, send the packet through it, close it.
DatagramSocket dsocket = new DatagramSocket();
dsocket.send(packet);
dsocket.close();
}
catch (Exception e) {
System.err.println(e);
System.err.println(usage);
}
}
}
Receiving Datagrams
Example 5-12 is a program that sits and waits to receive datagrams. When it
receives one, it prints out the contents of the datagram and the name of the host
that sent it.
To receive a datagram, you must first create a DatagramSocket that listens on a
particular port of the local host. This socket can receive packets sent only to that
particular port. Then, you must create a DatagramPacket with a byte buffer into
which datagram data is stored. Finally, you call the DatagramSocket.receive()
method to wait for a datagram to arrive on the specified port. When it does, the
Search WWH ::




Custom Search