How do I create a simple Datagram client?
Writing code for a UDP client is similar to that for a server (See http://www.jguru.com/jguru/faq/view.jsp?EID=206227). Again, we need a DatagramSocket and a DatagramPacket. The only real difference is that we must specify the destination address with each packet, so the form of the DatagramPacket constructor used here specifies the destination host and port number. Then, of course, we initially send packets instead of receiving.
- First allocate space to hold the data we are sending and
create an instance of DatagramPacket to hold the data.
byte buffer = new byte; int port = 1234; InetAddress host = InetAddress.getByName("jguru.com"); DatagramPacket packet = new DatagramPacket(buffer, buffer.length, host, port);
- Create a DatagramSocket and send the packet using this socket.
DatagramSocket socket = new DatagramSocket(); socket.send(packet);
The DatagramSocket constructor that takes no arguments will allocate a free local port to use. You can find out what local port number has been allocated for your socket, along with other information about your socket if needed.
// Find out where we are sending from InetAddress localHostname = socket.getLocalAddress(); int localPort = socket.getLocalPort();
The full source for a UDP echo client and server can be downloaded from the following links: