Reader Level:
ARTICLE

Networking in JAVA

Posted by Abhishek Dubey Articles | Java February 20, 2012
In this article we are exploring networking using TCP/IP protocols and try to make a small server and clients and show some information.
  • 0
  • 0
  • 9287

Introduction

A computer network is an interconnected collection of computers. The node of a network communicates others using a wired/wireless medium. This communication is actually carried between two processes residing in two different machines. The processes on one machine initiates the request and another responds to the request and another responds to the requests. The initiator is the client and the responder is the server.

TCP Protocol Suite

The TCP/IP protocol suite contains a number of  protocols. Its a four layer model followed by the network s. The internet also follows the same model. The client and server applications created by the user reside at the Application layer. They interact with the transport layer using the socket API. Java provide a package java.net. The transport layer take the data from takes data from application layer (sender) and breaks up in to segment attached the port number used by application to the data and passes in to the network layer. Depending upon the protocols used.

TCP/IP models figure

TCPIP Diagram.jpg

Socket

Network programming revolves around the concept of sockets. A socket is one end-point of a two-way communication link between two programs running on the network. In Java sockets are created with the help of Socket classes and these class are found in the java.net package. There are separate classes in the java.net package for creating TCP sockets and UDP sockets. The client socket is created with the help of the Socket class and the server socket is created using the ServerSocket class.

socket figure

socket2.jpg

Syntax

// for tcp client side
Socket s= new Socket (InetAddress adr, int port);

//for server side
ServerSocket ss= new ServerSocket (InetAddress adr, int port)

Step 1 : Creating a Socket on the client side (code):

// importing the usefull package like net and io
import java.net.*;
import java.io.*;
class MySocket
{
public
static void main(String[] args)
{ 
   try
{

            // using socket class constructor create socket

             Socket s =new Socket(InetAddress.getLocalHost(),15);

             System.out.println("your socket is created");   

             // using method of socket class find the local address

             System.out.println("Local Address :"+s.getLocalAddress());

             // using method of socket class find the local host

             System.out.println("Local Host :"+InetAddress.getLocalHost());

             // using method of socket class find the local port number

             System.out.println("Local Port :"+s.getLocalPort() );

             // using method of socket class find the local address 

             System.out.println("Inet Address :"+s.getInetAddress());

             // creating input stream by help of method getInputStream()

             InputStream in =s.getInputStream();

            // Buffered reader object is created to read strings from the socket.The Byte Stream is converted to character stream using the   
            InputStreamReader

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

             String str= null;

             while((str=br.readLine())!=null)

               System.out.println(str);

                in.close();

                s.close();

                    // catch exception is printing

              }catch(Exception e)

              {

                     System.out.println(e);

              }
     }

}


Step 2 : Creating a TCP Server (code):

import java.io.*;
import java.net.*;
import java.util.*;
class MyServerSocket
  {
   public
static void main(String[] args)
      {
     
   try {
              ServerSocket ss=new ServerSocket(15);
               while(true)
                     {
                       Socket client =ss.accept();
                       System.out.println("socket is created");
                   // using method of ServerSocket class find the client  address
                     System.out.println("client inet Address :"+client.getInetAddres());
                    // using method of ServerSocket class find the client port number
                     System.out.println("client Port number :"+client.getPort() );
                     // getting the out put stream to the client socket
                     OutputStream out=client.getOutputStream();
                     //gettimg the date so make the object of callender class
                     Calendar c=Calendar.getInstance();
                     System.out.println("server date and time :"+c.getTime());
                     PrintWriter pw = new PrintWriter(out,true);
                      pw.close(); 
                     }
           
              }
              catch (Exception e)
              {
                     System.out.println(e);
              }               
       }
}


Output

First the server is started and waits for a client.

cmdserverblank.jpg

Then a Client is started and the output is as follows:

cmd of client.jpg

After the client starts then the server output is:

cmd after server.jpg
 
Resources

Use of ByteStreams and CharacterStreams in JAVA
Learning JDBC (Java Database Connectivity)Working with Hibernate - Display , Insert, Update and Delete in JAVAMatrix Multiplication in Java Java Packages - Creation And Use

COMMENT USING

Trending up