Architecture & DesignExploring the Java Networking APIs

Exploring the Java Networking APIs

Developer.com content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

Java is one of the premier programming languages used in modern network programming. Network programming support refers not only to providing APIs to enable establishing communication between two or more remote computers but also to provide all the necessary means by which even a novice programmer can access network resources easily. There is a complete package dedicated for this cause in Java, called the java.net package. Networking is by far a large and complicated topic, but in this article we’ll try explore some of the key points of network programming through the lens of Java APIs.

A Networking Overview

The concept of socket forms the basis of modern network programming. It refers to the communicating endpoints between two computers in a network. This idea of socket owes its origin in 80s back to the release of 4.2 BSD UNIX. Since then, it has become a de-facto paradigm of network programming. Socket programming enables us to establish communication between multiple clients all at once. The type of information communicated also varies according to the port number used along with the socket. Therefore, a single computer can communicate not only with multiple clients but also with multiple type of information.

During network transmission, the data is broken into smaller chunks, called packets, which then are sent to an address across the network. The norms of this communication are called the routing protocol. Internet Protocol (IP) is such a low-level protocol which transmits information to the destination address but does not guarantee that the said packet will be delivered. This means that the communication according to this protocol is marked by unreliability. There is another protocol called the Transmission Control Protocol (TCP), which is a high level protocol that manages transmission of packets in a reliable manner by sorting and re-transmitting undelivered packets to the destination address.

But the problem with TCP is that it is a connection-oriented protocol; this means that, prior to information transmission, a connection must be established and this connection must be rigidly held onto throughout the communication process. The connection must be explicitly released at the end of the communication. This ensures reliability, no doubt, but also wastes bandwidth by holding on to the channel even if no data transmission occurs at a particular moment. There is another version of TCP protocol, called the User Datagram Protocol (UDP), that answers this problem aptly. This protocol supports transmission that is fast, and connectionless, but has an unreliable exchange of packets. Therefore, the reliability or unreliability of data transmission is directly associated with the type of connection established, whether it is connection oriented or connection less; it depends respectively.

The protocol, therefore, is called TCP/IP. This protocol reserves 1024 ports to determine some higher-order protocols. To allay confusion, note that these specific protocols determine the type of information transmitted, whereas the low-level protocols (TCP/IP) are concerned only with the mechanism of how data is to be transmitted by conditioning the information into smaller chunks called packets without caring about the type of information it contained.

We are familiar with many of these specific protocols. Usually, a specific port number is identified by a particular protocol. This however, may be overridden by the server administrator for security reasons. But, in general, they are associated with port number as follows: File Transfer Protocol or FTP (21), Telnet (23), Simple Mail Transfer Protocol or SMTP (25), whois (43), Hyper Text Transfer Protocol or HTTP (80), and so forth. The communication received in a particular port determines how the client will interact with the data received. For example, data received in port 80 (HTTP) is meant to be understood only by the browser; that means it contains hypertext pages and images.

Lastly, the key component of network communication is the address of the computer itself, called the IP (Internet Protocol) address. Every computer in a network must have one. An IPv4 (IP address version 4) address is a 32-bit value organized as four chunks of 8-bit values. Another recent development of the IP address is the IPv6 (version 6), which uses a 128-bit value in eight 16-bit chunks to represent an address. There are several advantages and disadvantages of one over the other, but when programming, we need not bother about them as much because it is automatically handled by Java.

Networking in Java

Java supports both TCP and UDP protocol where TCP is used for reliable connection-oriented, stream-based I/O across the network and UDP is used for fast, unreliable, point-to-point datagram connection. The tag “unreliability” associated with UDP is somewhat an understatement. In practice, data transmission through UDP it is quite reliable and the use of this model should only be discarded when the higher emphasis of communication is laid upon absolute reliability. Other than that, UDP is quite effective on most occasions and should be used for all practical reasons.

There are several classes and interfaces contained in the java.net package. Here we’ll consider a few of the important ones.

Always keep the Java API documentation handy as a ready reference and for more details on the APIs.

The Java InetAddress Class

One of the most important classes in the java.net package is the InetAddress. This class encapsulates the domain name as well as the numeric value of the IP address. We can interact with the IP host in either format. There is no constructor defined in this class. Therefore, the only way to create an object of this class is through one of several overloaded static factory methods defined, such as:

static InetAddress[] getAllByName(String host)
static InetAddress getByAddress(byte[] addr)
static InetAddress getByAddress(String host, byte[] addr)
static InetAddress getByName(String host)
static InetAddress getLocalHost()
static InetAddress getLoopbackAddress()

A loopback address is an IP address that is used to test communication and transportation infrastructure within itself. It routes signals and streams within the computer as a process of communication introspection. In IPv4, the common address used as a loopback address is 127.0.0.1; however, the range may be extended to 127.255.255.255.

The localhost is a hostname that refers to the computer itself.

Here is a quick example of how to use this class:

package org.mano.example;

import java.net.InetAddress;
import java.net.UnknownHostException;

public class Main {

   public static void main(String[] args)
         throws UnknownHostException{

      InetAddress address1=InetAddress
         .getLocalHost();
         System.out.println(address1);

         InetAddress address2=InetAddress
            .getLoopbackAddress();
         System.out.println(address2);

         InetAddress address3=InetAddress
            .getByName("www.youtube.com");
         System.out.println(address3);

         InetAddress[] arr=InetAddress
            .getAllByName("www.google.com");
         for(InetAddress a: arr){
            System.out.println(a);
      }
   }
}

Java also provides two more classes that extend this class, called Inet4Address and Inet6Address, to specifically support IPv4 and IPv6, respectively. Because these two classes are actually subclasses of InetAddress, a reference to this class can refer to either instance of Inet4Address or Inet6Address.

The Java URL Class

URL stands for Uniform Resource Locator; it is the most common way to refer to a resource in the Internet. It is a resource-locating address because the Internet today is a loose collection of many higher-level protocols and file formats. A URL provides a scalable naming scheme to uniquely identify or address information in the Internet. The URL class of Java provides the necessary APIs to access information across the Internet.

Here is a quick example to illustrate its usage:

package org.mano.example;

import java.net.MalformedURLException;
import java.net.URL;

public class Main {

   public static void main(String[] args)
         throws MalformedURLException{

      URL url=new URL("http://www.developer.com"
         + "/design/working-with-javafx-chart-apis/");

      System.out.println(url.getProtocol());
      System.out.println(url.getHost());
      System.out.println(url.getFile());
      System.out.println(url.toExternalForm());
   }
}

Java provides another class, called the URLConnection, to access the attributes of remote resource. It is a general-purpose utility class that provides several methods that may be used to examine the properties of document content.

package org.mano.example;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class Main {

   public static void main(String[] args)
         throws MalformedURLException, IOException{

      URL url=new URL("http://www.developer.com"
         + "/design/working-with-javafx-chart-apis/");

      URLConnection urlconn=url.openConnection();
      System.out.println(urlconn.getContentType());

      InputStream in=urlconn.getInputStream();
      int ch;
      while((ch = in.read())!= -1){
         System.out.print((char)ch);
      }
      in.close();
   }
}

The program establishes a HTTP (Port 80) connection to the URL specified and retrieves the header values of the site and content.

There is subclass of URLConnection, called the HttpURLConnection, which is specific to HTTP protocol. It may be instantiated in the same manner as URLConnection and have the same methods. The only difference is that this class is specific to HTTP protocols.

The Java URI Class

Java has another class, called the URI (Uniform Resource Identifier). The URI is a standard way to identify a resource. It is similar to the URL class; in fact, URL is a subset of the URI class. Conceptually, a URL enables us to locate a resource in addition to identifying a resource which is what URI is for. This means that all URLs are URIs, but the reverse is not true. Therefore, armed with this idea, it is not very difficult to choose the right class in Java? Can’t decide what to choose—URI or URL? No more confusion.

The Cookies

Java provides classes such as HttpCookie, CookieManager, CookieHandler, and interfaces such as CookiePolicy and CookieStore to deal with a stateful HTTP session, all within the java.net package. The classes are quite handy when working with Servlets and JSPs where we generally create a HTTP session.

Creating a TCP Client and Server in Java

The simplest way to create a bidirectional, reliable, point-to-point, stream-based connection between hosts on the Internet is by implementing TCP sockets. Java provides all the necessary means to implement one from the scratch. Here is a complete discussion on how to create one, specifically a client-server application using TCP sockets.

Creating a UDP Client and Server in Java

Java’s way of transmitting datagrams over the network is through UDP protocol. It may be called a lightweight data transmission over TCP network, because TCP includes a lot of overhead to maintain the sanity of transmission, such as congestion control over crowded a network, packet re-transmission strategy due to packet loss, and so on. These make it a heavy and costly way to maintain connectivity between hosts. In that sense, datagram, though a unreliable transmission strategy, is lightweight and does not care about the packet loss once it is send over the network. Sometime this careless strategy is exactly what we need, rather than opting for a heavy TCP connection. Here is an example of how to create a UDP client-server socket application.

Conclusion

There are many other classes in the java.net package. These few are perhaps the basic classes to deal with anything related to implementing a network application in Java. However, note that the real strength of the developer lies in one’s conceptual base in networking as a subject and not in any programming language. Having said that, it is worth mentioning that Java makes it easy to kick-start network programming, even for a budding programmer. During the inception of Java, people thought it is a language for Internet programming. Such a notion certainly has some value because we can see the extension of API support it provides in this respect.

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories