Java – Networking

Java Networking is a concept of connecting two or more computing devices together so that we can share resources. The java.net package of the J2SE APIs contains a collection of classes and interfaces that provide the low-level communication details.

Java socket programming provides facility to share data between different computing devices. The java.net package provides support for the two common network protocols.

  • TCP − TCP stands for Transmission Control Protocol, which allows for reliable communication between two applications. TCP is typically used over the Internet Protocol, which is referred to as TCP/IP.
  • UDP − UDP stands for User Datagram Protocol, a connection-less protocol that allows for packets of data to be transmitted between applications.

This post gives a good understanding on the following two subjects.

  • Socket Programming − This is the most widely used concept in Networking and it has been explained in very detail.
  • URL Processing − This would be covered separately. Click here to learn aboutURL Processing in Java language.

Protocol

A protocol is a set of rules basically that is followed for communication. For example:

  • TCP
  • FTP
  • Telnet
  • SMTP
  • POP etc.

Port Number

The port number is used to uniquely identify different applications. It acts as a communication endpoint between applications. The port number is associated with the IP address for communication between two applications.

Socket

A socket is an endpoint between two way communication. A client program creates a socket on its end of the communication and attempts to connect that socket to a server.

The java.net.Socket class represents a socket, and the java.net.ServerSocket class provides a mechanism for the server program to listen for clients and establish connections with them.

InetAddress Class Methods

This class represents an Internet Protocol (IP) address. Here are following usefull methods which you would need while doing socket programming:

  • static InetAddress getByAddress(byte[] addr) – Returns an InetAddress object given the raw IP address.
  • static InetAddress getByAddress(String host, byte[] addr) – Creates an InetAddress based on the provided host name and IP address.
  • static InetAddress getByName(String host) – Determines the IP address of a host, given the host’s name.
  • String getHostAddress() – Returns the IP address string in textual presentation.
  • String getHostName() – Gets the host name for this IP address.
  • static InetAddress InetAddress getLocalHost() – Returns the local host.
  • String toString() – Converts this IP address to a String.

Socket Client Example

The following GreetingClient is a client program that connects to a server by using a socket and sends a greeting, and then waits for a response.

Example:

// File Name GreetingClient.java
import java.net.*;
import java.io.*;

public class GreetingClient {

   public static void main(String [] args) {
      String serverName = args[0];
      int port = Integer.parseInt(args[1]);
      try {
         System.out.println("Connecting to " + serverName + " on port " + port);
         Socket client = new Socket(serverName, port);
         
         System.out.println("Just connected to " + client.getRemoteSocketAddress());
         OutputStream outToServer = client.getOutputStream();
         DataOutputStream out = new DataOutputStream(outToServer);
         
         out.writeUTF("Hello from " + client.getLocalSocketAddress());
         InputStream inFromServer = client.getInputStream();
         DataInputStream in = new DataInputStream(inFromServer);
         
         System.out.println("Server says " + in.readUTF());
         client.close();
      } catch (IOException e) {
         e.printStackTrace();
      }
   }
}

Socket Server Example

The following GreetingServer program is an example of a server application that uses the Socket class to listen for clients on a port number specified by a command-line argument.

Example:

// File Name GreetingServer.java
import java.net.*;
import java.io.*;

public class GreetingServer extends Thread {
   private ServerSocket serverSocket;
   
   public GreetingServer(int port) throws IOException {
      serverSocket = new ServerSocket(port);
      serverSocket.setSoTimeout(10000);
   }

   public void run() {
      while(true) {
         try {
            System.out.println("Waiting for client on port " + 
               serverSocket.getLocalPort() + "...");
            Socket server = serverSocket.accept();
            
            System.out.println("Just connected to " + server.getRemoteSocketAddress());
            DataInputStream in = new DataInputStream(server.getInputStream());
            
            System.out.println(in.readUTF());
            DataOutputStream out = new DataOutputStream(server.getOutputStream());
            out.writeUTF("Thank you for connecting to " + server.getLocalSocketAddress()
               + "\nGoodbye!");
            server.close();
            
         } catch (SocketTimeoutException s) {
            System.out.println("Socket timed out!");
            break;
         } catch (IOException e) {
            e.printStackTrace();
            break;
         }
      }
   }
   
   public static void main(String [] args) {
      int port = Integer.parseInt(args[0]);
      try {
         Thread t = new GreetingServer(port);
         t.start();
      } catch (IOException e) {
         e.printStackTrace();
      }
   }
}

Compile the client and the server and then start the server as follows:

$ java GreetingServer 6066
Waiting for client on port 6066...

Check the client program as follows.

Output

$ java GreetingClient localhost 6066
Connecting to localhost on port 6066
Just connected to localhost/127.0.0.1:6066
Server says Thank you for connecting to /127.0.0.1:6066
Goodbye!
Related Post