The best programs are written so that computing machines can perform them quickly and so that human beings can understand them clearly. A programmer is ideally an essayist who works with traditional aesthetic and literary forms as
well as mathematical concepts, to communicate the way that an algorithm works and to convince a reader that the results will be correct. Donald E. Knuth

Network Programming with Java

Networking is a practice of connecting two or more computing devices for sharing data and resources. Each device in a network is identified by an ip address and devices communicate with each other using protocols. Networking is a vast subject and it is not feasible to cover the networking concepts here. The aim of this section is to introduce you to network programming where we write Java programs which execute on different devices and communicate over network. The java.net package provide the APIs to develop such programs.

Socket Programming
A socket is an endpoint for communication between processes running on different machines. A socket consists of an ip address and a port number which uniquely identifies a running process on a system. IP Address identifies a machine and Port No. identifies the specific application ( process ). Socket programming deals with writing programs which communicate over network using sockets.

Client - Server Model
In a client-server model of computing, a server hosts a resource or a service which is accessed by clients. Often client and server communicates over network using sockets. A server creates a socket in its communication end and binds itself to a port and then listens ( waits ) for incoming connections from client. A client creates a socket in its end and connects to the listening server at the specified port.

Socket and ServerSocket Classes
The ServerSocket class is used by the server side program to obtain and bind to a port and listen for incoming connections from client. The Socket class is used by both client and server to communicate with each other. Now, we will write some sample programs to illustrate socket programming. We will run both client and server programs on the same machine and use the loopback ip address ( 127.0.0.1 ) to test these programs. We will use some random and large port numbers which are not likely to be any standard port number ( like port 80 is used for http ). A loopback address is a special IP address used to test network applications on a local machine.

Client to Server Communication ( One Way )
In the following application, client sends a message to the server. The server program ( MyServer.java ) should be executed first. Then client ( MyClient.java ) is run which connects to the server and sends a message.

Server Program
import java.io.*;
import java.net.*;
public class MyServer {
   public static void main(String args[]) {
      try {
         // Create a new server socket that listens at port 6999
         ServerSocket ss = new ServerSocket(6999);
         System.out.println("Server is lisenting ... ");
         Socket skt = ss.accept();//wait for connection from client on port 6999
         InputStream is = skt.getInputStream();
         ObjectInputStream ois = new ObjectInputStream(is);
         String msg = (String)ois.readObject(); // recieve message from client
         System.out.println("Server recieved message : " + msg);
         System.out.println("Server is exiting ... ");
         /* close open streams and socket */
         ois.close();
         is.close();
         skt.close();
         ss.close();
      } catch(Exception e) {
         System.out.println(e);
      }
   }
}
Run this program in your system  
Client Program
import java.io.*;
import java.net.*;
public class MyClient {
   public static void main(String args[]) {
      try {
         // create a new socket for communicating with the server
         Socket skt = new Socket("127.0.0.1", 6999);
         System.out.println("Connected to server");
         String msg = "Hello Server";
         OutputStream os = skt.getOutputStream();
         ObjectOutputStream oos = new ObjectOutputStream(os);
         oos.writeObject(msg); // send a message to server
         System.out.println("Sent a message to server");
         /* close open streams and sockets */
         oos.close();
         os.close();
         skt.close();
      } catch(Exception e) {
         System.out.println(e);
      }
   }
}
Run this program in your system  

Server to Client Communication ( One Way )
In the following application, server ( MySimpleServer.java ) sends a message to the client
( MySimpleClient.java ).

Server Program
import java.io.*;
import java.net.*;
public class MySimpleServer {
   public static void main(String args[]) {
      try {
         // Create a new server socket that listens at port 7999
         ServerSocket ss = new ServerSocket(7999);
         System.out.println("Server is lisenting ... ");
         Socket skt = ss.accept();//accept a connection from client on port 7999
         String msg = "Hello Client! Thanks for connecting";
         OutputStream os = skt.getOutputStream();
         ObjectOutputStream oos = new ObjectOutputStream(os);
         oos.writeObject(msg); // send a message to client
         System.out.println("Sent a message to client");
         System.out.println("Server is exiting ... ");
         /* close open streams and sockets */
         oos.close();
         os.close();
         skt.close();
         ss.close();
      } catch(Exception e) {
         System.out.println(e);
      }
   }
}
Run this program in your system  
Client Program
import java.io.*;
import java.net.*;
public class MySimpleClient {
   public static void main(String args[]) {
      try {
         // create a new socket for communicating with the server
         Socket skt = new Socket("127.0.0.1", 7999);
         System.out.println("Connected to server");
         InputStream is = skt.getInputStream();
         ObjectInputStream ois = new ObjectInputStream(is);
         String msg = (String)ois.readObject(); // recieve a message from server
         System.out.println("Recieved message from Server : " + msg);
         /* close open streams and sockets */
         ois.close();
         is.close();
         skt.close();
      } catch(Exception e) {
         System.out.println(e);
      }
   }
}
Run this program in your system  

Two way Chatting Application
Now we will write a chat application in which there will be two way communication i.e the client
( MyChatClient.java ) and server ( MyChatServer.java ) will send messages to each other.

Server Program
import java.io.*;
import java.net.*;
public class MyChatServer {
   public static void main(String args[]) {
      try {
         // Create a new server socket that listens at port 8999
         ServerSocket ss = new ServerSocket(8999);
         System.out.println("Server is lisenting ... ");
         Socket skt = ss.accept();//accept a connection from client on port 8999

         OutputStream os = skt.getOutputStream();
         ObjectOutputStream oos = new ObjectOutputStream(os);
         InputStream is = skt.getInputStream();
         ObjectInputStream ois = new ObjectInputStream(is);

         BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

         String rcv_msg, send_msg;
         while(true) {
            /* Recieve a message from client */
            System.out.println("Waiting for client to respond ... ");
            if((rcv_msg = (String)ois.readObject()) != null) {
               System.out.println("From Client : " + rcv_msg);
            }

            /* Send a message to client */
            System.out.print("\nTo Client : ");
            send_msg = br.readLine();
            oos.writeObject(send_msg);
         }
      } catch(Exception e) {
         System.out.println(e);
      }
   }
}
Run this program in your system  
Client Program
import java.io.*;
import java.net.*;
public class MyChatClient {
   public static void main(String args[]) {
      try {
         Socket skt = new Socket("127.0.0.1", 8999);
         System.out.println("Connected to server");

         InputStream is = skt.getInputStream();
         ObjectInputStream ois = new ObjectInputStream(is);
         OutputStream os = skt.getOutputStream();
         ObjectOutputStream oos = new ObjectOutputStream(os);

         BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

         String rcv_msg, send_msg;
         while(true) {
            /* Send a message to Server */
            System.out.print("To Server : ");
            send_msg = br.readLine();
            oos.writeObject(send_msg);

            /* Recieve a message from Server */
            System.out.println("Waiting for server to respond ... ");
            if((rcv_msg = (String)ois.readObject()) != null) {
               System.out.println("\nFrom Server : " + rcv_msg);
            }
         }
      } catch(Exception e) {
         System.out.println(e);
      }
   }
}
Run this program in your system  

InetAddress Class
This class encapsulates domain name and IP Address and provide methods for retrieving those information. Following program illustrates the use of this class.

import java.io.*;
import java.net.*;
public class InetAddressDemo {
   public static void main(String args[]) {
      try {
         String host = "www.csegeek.com";
         InetAddress ip = InetAddress.getByName(host);
         System.out.println("IP Address : " + ip.getHostAddress());
         System.out.println("Hostname : " + ip.getHostName());
      } catch(UnknownHostException uhe) {
         System.out.println("Host Not Found");
      } catch(Exception e) {
         System.out.println(e);
      }
   }
}

Back | Next