Java Reference
In-Depth Information
Example 5•10: ProxyServer.java (continued)
// Wait for them to exit
try { c2s.join(); s2c.join(); } catch (InterruptedException e) {}
}
}
}
Sending Datagrams
Now that we've thoroughly covered the possibilities of networking with sockets
and streams, let's examine how low-level networking can be done using data-
grams and packets. Example 5-11 and Example 5-12 show how you can imple-
ment simple network communication using datagrams. Datagram communication
is sometimes called UDP, for Unreliable Datagram Protocol. Sending datagrams is
fast, but the tradeoff is that that they are not guaranteed to reach their destination.
In addition, multiple datagrams are not guaranteed to travel to their destination by
the same route or to arrive at their destination in the order in which they were
sent. Datagrams are useful when you want low-overhead communication of non-
critical data and when a stream model of communication is not necessary. For
example, you might implement a multiuser chat server for a local area network
using datagrams.
To send and receive datagrams, you use the DatagramPacket and DatagramSocket
classes. These objects are created and initialized differently depending on whether
they send or receive datagrams. Example 5-11 shows how to send a datagram;
Example 5-12 shows how to receive a datagram and how to find who sent it.
To send a datagram, you first create a DatagramPacket , specifying the data to be
sent, the length of the data, the host to send it to, and the port on that host where
it is to be sent. You then use the send() method of a DatagramSocket to send the
packet. The DatagramSocket is a generic one, created with no arguments. It can be
reused to send any packet to any address and port.
Example 5•11: UDPSend.java
package com.davidflanagan.examples.net;
import java.io.*;
import java.net.*;
/**
* This class sends the specified text or file as a datagram to the
* specified port of the specified host.
**/
public class UDPSend {
public static final String usage =
"Usage: java UDPSend <hostname> <port> <msg>...\n" +
"
or: java UDPSend <hostname> <port> -f <file>";
public static void main(String args[]) {
try {
// Check the number of arguments
if (args.length < 3)
throw new IllegalArgumentException("Wrong number of args");
Search WWH ::




Custom Search