DatagraClient.java - A Datagram Client Application

This section provides a tutorial example on how to write a network application, DatagraClient.java, that creates a client socket, sends datagram packet to a datagram server.

The following program, called DatagraClient, acts as a client program to DatagramServer. It repeatedly sends a datagram packet to DatagramServer, and waits a return datagram packet:

/* DatagramClient.java
 * Copyright (c) HerongYang.com. All Rights Reserved.
 */
import java.io.*;
import java.net.*;
public class DatagramClient {
   public static void main(String[] args) {
      BufferedReader in = new BufferedReader(new InputStreamReader(
         System.in));
      PrintStream out = System.out;
      byte[] buf = new byte[1024];
      try {
         DatagramPacket dp = new DatagramPacket(buf, buf.length);
         dp.setAddress(InetAddress.getByName("localhost"));
         dp.setPort(7777);
         // binding to the default address and any free port
         DatagramSocket ds = new DatagramSocket();
         printDatagramSocketInfo(ds);
         String m = null;
         while (true) {
            // sending the text line from console to the remote system
            m = in.readLine();
            byte[] b = m.getBytes();
            dp.setData(b);
            dp.setLength(b.length);
            ds.send(dp);
            // sending the text line from the remote system to console
            dp.setData(buf);
            ds.receive(dp);
            m = new String(buf, 0, dp.getLength());
            out.println(m);
            if (m.equals(".")) break;
         }
      } catch (IOException e) {
         System.err.println(e.toString());
      }
   }
   private static void printDatagramSocketInfo(DatagramSocket s) {
      System.out.println("Datagram Socket Info:");
      if (s.isConnected()) {
         System.out.println("   Connected to a remote system.");
         System.out.println("   Remote address = "
            +s.getInetAddress().toString());
         System.out.println("   Remote port = "
            +s.getPort());
      } else {
         System.out.println("   Not connected to a remote system.");
      }
      System.out.println("   Local socket address = "
         +s.getLocalSocketAddress().toString());
      System.out.println("   Local address = "
         +s.getLocalAddress().toString());
      System.out.println("   Local port = "
         +s.getLocalPort());
   }
}

One DatagramPacket object is used for both sending data and receiving data. Two byte arrays are used in the program, "buf" contains the data received, "b" contains the data to be sent out.

With DatagramServer running in a command window, run DatagramClient in another command window, and type in:

Fish, I love you and respect you very much.
But I will kill you dead before this day ends.
.

You will see:

herong> java DatagramClient.java

Datagram Socket Info:
   Not connected to a remote system.
   Local socket address = 0.0.0.0/0.0.0.0:1035
   Local address = 0.0.0.0/0.0.0.0
   Local port = 1035
Fish, I love you and respect you very much.
.hcum yrev uoy tcepser dna uoy evol I ,hsiF
But I will kill you dead before this day ends.
.sdne yad siht erofeb daed uoy llik lliw I tuB
.

Note that the datagram socket constructor automatically picked up a free local port, 1035.

In the DatagramServer window, you will see the following output:

Datagram Socket Info:
   Not connected to a remote system.
   Local socket address = 0.0.0.0/0.0.0.0:7777
   Local address = 0.0.0.0/0.0.0.0
   Local port = 7777
Datagram Packet Info:
   Remote socket address = /127.0.0.1:1035
   Remote address = /127.0.0.1
   Remote port = 1035
   Data length = 43
Datagram Socket Info:
   Not connected to a remote system.
   Local socket address = 0.0.0.0/0.0.0.0:7777
   Local address = 0.0.0.0/0.0.0.0
   Local port = 7777
Datagram Packet Info:
   Remote socket address = /127.0.0.1:1035
   Remote address = /127.0.0.1
   Remote port = 1035
   Data length = 46
Datagram Socket Info:
   Not connected to a remote system.
   Local socket address = 0.0.0.0/0.0.0.0:7777
   Local address = 0.0.0.0/0.0.0.0
   Local port = 7777
Datagram Packet Info:
   Remote socket address = /127.0.0.1:1035
   Remote address = /127.0.0.1
   Remote port = 1035
   Data length = 1

As you can see, DatagramServer and DatagramClient worked perfectly. You can even run multiple instances of DatagramClient, and DatagramServer will handle them correctly.

Table of Contents

 About This JDK Tutorial Book

 JDK (Java Development Kit)

 Java Date-Time API

 Date, Time and Calendar Classes

 Date and Time Object and String Conversion

 Number Object and Numeric String Conversion

 Locales, Localization Methods and Resource Bundles

 Calling and Importing Classes Defined in Unnamed Packages

 HashSet, Vector, HashMap and Collection Classes

 Character Set Encoding Classes and Methods

 Character Set Encoding Maps

 Encoding Conversion Programs for Encoded Text Files

 Java Logging

 Socket Network Communication

Datagram Network Communication

 What Is a Datagram?

 Establishing a Datagram Communication Link

 DatagramServer.java - A Datagram Server Application

DatagraClient.java - A Datagram Client Application

 DOM (Document Object Model) - API for XML Files

 SAX (Simple API for XML)

 DTD (Document Type Definition) - XML Validation

 XSD (XML Schema Definition) - XML Validation

 XSL (Extensible Stylesheet Language)

 Message Digest Algorithm Implementations in JDK

 Private key and Public Key Pair Generation

 PKCS#8/X.509 Private/Public Encoding Standards

 Digital Signature Algorithm and Sample Program

 "keytool" Commands and "keystore" Files

 KeyStore and Certificate Classes

 Secret Key Generation and Management

 Cipher - Encryption and Decryption

 The SSL (Secure Socket Layer) Protocol

 SSL Socket Communication Testing Programs

 SSL Client Authentication

 HTTPS (Hypertext Transfer Protocol Secure)

 Outdated Tutorials

 References

 Full Version in PDF/EPUB