Wednesday, 23 September 2015

Date-Time Server and Client program in JAVA

Server-Client Visualization
Server-Client Visualization
Networking is very powerful area which allows different machines to get connected. Human life became very easy through the networking concepts. Lets start the discussion of the same with understanding basics of the Networking & How to do it in JAVA.

Networking allows communication between 2 or more computers. The diagram shown here is just for example to get an idea of how networking is done. Only one Server & 8 Clients are shown in the diagram. Clients makes requests to Server & Server serves those requests.

          We must consider following scenarios,
1. Single Server & Single Client. Both are on same machine.
2. Single Server & Single Client. Both are on different machines.
3. Single Server & Multiple Clients.
4. Multiple Servers & Multiple Clients.

Today, I am going to discuss the very first & basic scenario where only one Server & one Client is present. Client will request Date and Time on Server; where in the response of the same Server will give answer as current Date and Time on Server. So, lets go into implementation details of the same program in Java.

JAVA provides "" package which contains classes required for network programming. Communication over a network takes place via a protocol like Internet Protocol (IP), Transmission Control Protocol (TCP), User Datagram Protocol (UDP). Any Protocol is set of rules & standards required to complete communication. A protocol specifies the format of data being sent over a network, along with how and when it is sent. At the other end of communication, the protocol also defines how the data is received along with its structure and what it means. On the internet, we have additional protocols like Hyper Text Transfer Protocol (HTTP), File Transfer Protocol (FTP).

TCP/IP networking is appropriate for most networking needs. It provides a serialized, predictable and reliable stream of packet data. However TCP includes many complex algorithms for dealing with congestion control on crowded networks as well as pessimistic expectations about packet loss. Datagrams are alternative to TCP/IP protocols. They support fast and connection-less transport of packets. However they are unreliable as there is no assurance that the packet is not damaged in transit or that whoever sent it is still there to receive a response. However UDP relies on few network resources.

A key component of the internet is the address. An internet address or IP Address is a 32 bit (IPv4. 128 bit in IPv6) number that uniquely identifies each computer physically attached to the internet. This name can be associated with a Domain Name. An internet domain name is mapped to an IP address by the Domain Naming Service (DNS).

At core of JAVA's networking support is the concept of a Socket. A socket is a software endpoint that establishes bidirectional communication between a Server program and one or more Client program. The Socket associates the server program with a specific port on the machine and from where it runs any client program anywhere in the network. Sockets are at the foundation of modern networking because a socket allows a single computer (Server) to serve many different Clients at once as well as many different types of information. This is accomplished through the use of a port which is numbered socket on a particular machine. A Server is allowed to accept multiple Clients connected to the same port number, though each session is unique. To manage multiple Clients connections a Server must use Multithreading.

Once a connection has been established, TCP/IP reserves specific ports for specific purposes for example 21 for FTP, 23 for Telnet, 25 for email, 80 for HTTP, etc. The protocol determines how the client should interact with the port. The lower 1024 ports are reserved for specific protocols , So we need to use ports from 1025 and later for our customized functions or communications. A Port is a 16 bit number that identifies each service offered by a network server.

The package contains following classes:
1. InetAddress
2. Socket
3. ServerSocket
4. DatagramSocket
5. DatagramPacket

1. InetAddress class: 
This class can be used to determine the addresses over the internet. By supplying the host name. we can determine the IP address of the machine. To create an instance of InetAddress, we have to use inbuilt static methods which returns an instance of that class. Commonly used methods are,

a) getLocalHost()
b) getByName(String host-name).

2. Socket class:
Java performs the network communication through Sockets. There are two main types of sockets, TCP/IP Sockets & Datagram Sockets. Also there are two types of TCP/IP Sockets, ServerSocket class for Servers and Socket class for Clients. The creation of socket class object establishes the connection between Client & Server. It has two constructors,

a) Socket(String host-name, int port) throws IOException, UnknownHostException
b) Socket(InetAddress ip-address, int port) throws IOException

It also has following important instance methods,

a) InetAddress getInetAddress()
b) int getPort()
c) int getLocalPort()

3. ServerSocket class:
It is mainly a listener class which waits for clients to connect. Socket is used initiate the communication. An accept() method is used to make server wait for client to get connected to it. Once its connected it returns an object of server class. To manage multiple clients a server must use multithreading. One of its constructor is,

a) ServerSocket (int port) throws IOException

4. Datagram Sockets:
Datagram sockets uses Datagram protocol which does not guarantees the delivery of messages. This is like having a dial-up network connection where user is connected to net temporarily. Some of its important constructors are,

a) DatagramSocket() throws SocketException
b) DatagramSocket(int port) throws SocketException
c) DatagramSocket(int port, InetAddress ip-address) throws SocketException

Also it has two important methods,
a) void send(DatagramPacket packet) throws IOException
b) void receive(DatagramPacket packet) throws IOException

5. DatagramPacket:
The object of this class is a container or a packet of information  which is sent over the internet. Some of its important constructors are,

a) DatagramPacket(byte data[], int size)
b) DatagramPacket(byte data[],int size,InetAddress ip-address, int port)

After getting all the basics of Networking & required methods in JAVA, this is time to go for the execution of one program. Following is the program in which One Server & one Client is present. Client gets connected to Server asks the current Date & Time of Server. In Reply Server sends its current Date & Time to Client.

Following is the sample code of the implementation. You can also get it from my GitHub repository.
Note: First execute Server program & after that execute Client program.

Server Program:

import java.util.Date;
 * @author YogeshD
public class Server_DT {

     * @param args the command line arguments
    public static void main(String[] args)throws IOException {
        // TODO code application logic here
        //Step 1. Reserve a port number on the Server to offer this service
        ServerSocket ss= new ServerSocket(5000);
        //(Optional)To confirm Server Reserved specified port or not
        System.out.println("The Server has reserved port No.: "+ss.getLocalPort()+" for this Service");
        //Step 2. Now create a Client Socket on Server for Bidirectonal Communication.
        //Socket is created only when client communicates with the server
        Socket cs=ss.accept();
        //To confirm Server communicated through the socket or not
        System.out.println("Client with IP Address "+cs.getInetAddress()+" has communicated via port No.: "+cs.getPort());
        Date d=new Date();
        String s="Current Date & Time on Server is:"+d;
        //Send String s to client via client socket
        PrintWriter toclient=new PrintWriter(cs.getOutputStream(),true);

Client Program:


 * @author YogeshD
public class Client_DT {

     * @param args the command line arguments
    public static void main(String[] args) throws UnknownHostException,IOException {
        // TODO code application logic here
        //Step 1. Create a client socket to connect to Server
        Socket cs= new Socket("LocalHost",5000);
        //To confirm Client is communicating through the port
        System.out.println("Client "+cs.getInetAddress()+" is communicating from port No.: "+cs.getPort());
        //Receive Date Sent by Server
        BufferedReader fromserver=new BufferedReader(new InputStreamReader(cs.getInputStream()));

==>Posted By Yogesh B. Desai

Next Post: Java Home Page

Previous Post: Bouncing Ball Program in JAVA using Multithreading and Applet

You are Visitor Number:
free counter


  1. Thanks for the post and great tips.Furthermore, journalists like to use this to stay anonymous on the web. Some people like to use this browser to just stay anonymous in general. If you want to belong become learning for Java Real-Time Training and Live High-Level Experience instructor Trained from Java Training Programme Course to reach us
    Java Training in Chennai
    Java Training Center with Placement in Chennai