Networking in Java

Introduction

Networking is the concept of connecting multiple remote or local devices together. Java program communicates over the network at application layer.
All the Java networking classes and interfaces use java.net package. These classes and interfaces provide the functionality to develop system-independent network communication.

The java.net package provides the functionality for two common protocols:

TCP (Transmission Control Protocol)
TCP is a connection based protocol that provides a reliable flow of data between two devices. This protocol provides the reliable connections between two applications so that they can communicate easily. It is a connection based protocol.

UDP (User Datagram Protocol)
UDP protocol sends independent packets of data, called datagram from one computer to another with no guarantee of arrival. It is not connection based protocol.

Networking Terminology

i) Request and Response
When an input data is sent to an application via network, it is called request.
The output data coming out from the application back to the client program is called response.

ii) Protocol
A protocol is basically a set of rules and guidelines which provides the instructions to send request and receive response over the network.
For example: TCP, UDP, SMTP, FTP etc.

iii) IP Address
IP Address stands for Internet protocol address. It is an identification number that is assigned to a node of a computer in the network.
For example: 192.168.2.01
Range of the IP Address
0.0.0.0  to  255.255.255.255

iv) Port Number
The port number is an identification number of server software. The port number is unique for different applications. It is a 32-bit positive integer number having between ranges 0 to 65535.

v) Socket
Socket is a listener through which computer can receive requests and responses. It is an endpoint of two way communication link. Every server or programs runs on the different computers that has a socket and is bound to the specific port number.

Java Socket Programming

Socket provides an endpoint of two way communication link using TCP protocol. Java socket can be connection oriented or connection less. TCP provides two way communication, it means data can be sent across both the sides at same time.

Socket Class

The java.net.Socket class is used to create a socket so that both the client and the server can communicate with each other easily. A socket is an endpoint for communication between two computers. The Socket class inherits the Object class and implements the Closeable interface.

Socket Class Constructors

ConstructorDescription
Socket()Creates an unconnected socket, with the system-default type of SocketImpl.
public Socket(InetAddress address, int port)Creates a stream socket with specified IP address to the specified port number.
public Socket(InetAddress host, int port, boolean stream)Uses the DatagramSocket.
public Socket(InetAddress address, int port, InetAddress localAddr, int local port)Creates a connection with specified remote address and remote port.
public Socket(Proxy, proxy)Creates a connectionless socket specifying the type of proxy.
protected Socket(SocketImpl impl)Creates a connectionless Socket with a user-specified SocketImpl.

ServerSocket Class

Socket class is used to create socket and send the request to the server. Java ServerSocket class waits for request to come over the network.  It works on the basis of request and then returns a result to the request. It implements the Closeable interface.

ServerSocket Class Constructors

ConstructorDescription
ServerSocket()Creates an unbound server socket.
ServerSocket(int port)Creates a server socket, bound to the specified port.
ServerSocket(int port, int backlog)Creates a server socket, bound to the specified port, with specified local port.
ServerSocket(int port, int backlog, inetAddress bindAddrs)Creates a server socket, bound to specified port, listen backlog, and IP address.


Example: Implementing the ServerSocket class & its methods

import java.io.*;
import java.net.*;
public class SerSocket
{
   public static void main(String args[])
   {
      int port=8080;
      try
      {
          ServerSocket ss = new ServerSocket(port);
          System.out.println("Server initialized on port: " + port);
          ss.getLocalPort();
          ss.getInetAddress();
          {
              while(true)
              ss.accept();
          }
       }
       catch (SocketException e)
       {
           System.out.println("Socket error");
       }
       catch ( IOException e)
       {
           System.out.println("An I/O Exception Occurred!");
       }
    }
}


Output:
Server initialized on port: 8080

Example: Generating Request and Response in Client and server Application

// ClientDemo.java

import java.io.InputStream;
import java.io.DataInputStream;
import java.net.Socket;
public class ClientDemo
{
    public static void main(String args[])
    {
        try
        {
            Socket s = new Socket("localhost", 7777);
            InputStream in = s.getInputStream();
            DataInputStream dis = new DataInputStream(in);
            String msg = dis.readLine();
            System.out.println("Server message is: "+ msg);
            dis.close();
            s.close();
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }
}


// ServerDemo.java

import java.io.OutputStream;
import java.io.DataOutputStream;
import java.net.Socket;
import java.net.ServerSocket;
public class ServerDemo
{
    public static void main(String args[])
    {
        try
        {
            ServerSocket ss = new ServerSocket(7777);
            System.out.println("Server is ready.");
            Socket s = ss.accept();
            System.out.println("COnnection created.");
            System.out.println("Sent message to client.");
            OutputStream out = s.getOutputStream();
            DataOutputStream dos = new DataOutputStream(out);
            dos.writeBytes("Welcome");
            dos.close();
            s.close();
            ss.close();
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }
}


Compilation: Both Client and Server program run on the different consol.