Java Networking

Java Networking is the mechanism of sharing data among one of or more computing devices by creating networks. In order to share resources or data among multiple computing devices, Java Socket programming is used.

The J2SE APIs provides java.net package. This package has all the classes and interfaces needed to create connections through low level communications in Java Networking. java networking

Network Protocols

There are two main types of network protocols in Java Networking. Both of them are defined below:

  • TCP: TCP stands for Transmission Control Protocol. It is also referred as IP that provides secure connection between two applications over the internet.
  • UDP: UDP stands for User Datagram Protocol. It is a connectionless protocol that transfers data from one application to another in the form of packets.

Both of these network protocols can be established using java.net package. Below list shows the names of classes present in the package used in Java Networking:

  • Authenticator
  • CacheRequest
  • CacheResponse
  • ContentHandler
  • CookieHandler
  • CookieManager
  • DatagramPacket
  • DatagramSocket
  • DatagramSocketImpl
  • InterfaceAddress
  • JarURLConnection
  • MulticastSocket
  • InetSocketAddress
  • InetAddress
  • Inet4Address
  • Inet6Address
  • IDN
  • HttpURLConnection
  • HttpCookie
  • NetPermission
  • NetworkInterface
  • PasswordAuthentication
  • Proxy
  • ProxySelector
  • ResponseCache
  • SecureCacheResponse
  • ServerSocket
  • Socket
  • SocketAddress
  • SocketImpl
  • SocketPermission
  • StandardSocketOptions
  • URI
  • URL
  • URLClassLoader
  • URLConnection
  • URLDecoder
  • URLEncoder
  • URLStreamHandler

Socket Class

In Java Networking the java.net.Socket class is used to define a socket that creates a connection between client and server. In this way communication is established. The socket used by client is created by the instance object of Socket class. Whereas the server socket is the object of Socket class that the accept() method returns. The table below shows the list of main methods of Socket class, along with their descriptions used in java networking.

Sr. No.MethodDescription
1.public Socket(String host, int port) throws UnknownHostException, IOExceptionThis method with host and port input parameters is used to connect the specified server to the specified port. If the connection is established successfully then the method throws no exception.
2.public Socket(InetAddress host, int port) throws IOExceptionThis method is same as the above method. The only difference is that the host is passed as an object of InetAddress.
3.public Socket(String host, int port, InetAddress localAddress, int localPort) throws IOExceptionThis method is used to connect the specified host and port. It also creates a socket on the local host at the specified address and port number.
4.public Socket(InetAddress host, int port, InetAddress localAddress, int localPort) throws IOExceptionThis method is same as above. The only difference is that it takes host parameter as an InetAddress object instead of a String.
5.public Socket()This method is used to create unconnected socket. This socket can later be connected to a server using the connect() method.
Socket Class Methods (Java Networking)

ServerSocket Class

In Java Networking the java.net.ServerSocket class is used to create server applications. These applications secure a port and get all the client requests. The below table shows the list of important methods and their description.

Sr. No.MethodDescription
1.public ServerSocket(int port) throws IOExceptionThis method creates a server socket for a designated port. It shows error if the port is already occupied by any other application.
2.public ServerSocket(int port, int backlog) throws IOExceptionThis method creates a server socket and as well as creates a backlog to make a waiting queue of incoming client requests.
3.public ServerSocket(int port, int backlog, InetAddress address) throws IOExceptionThis method performs all the functions explained in above methods and additionally the InetAddress parameter specifies a local IP address. This specific IP address is used by the server. The server only accepts requests from that IP address.
4.public ServerSocket() throws IOExceptionThis method when called without parameters, it is used to create an unbound server socket.
5.public void bind(SocketAddress host, int backlog)This method is used with ServerSocket() method to bind the server socket.
6.public int getLocalPort()This method returns the port number to which the server is bound. It is needed in the situation where you don’t know the port number, when the server selects a port number itself.
7.public Socket accept() throws IOExceptionThis method waits for an incoming client requests. Until then it blocks all requests, waiting for a client to connect to a server. It times out the socket for infinitely long time if the time out value is not set using the  setSoTimeout() method.
8.public void setSoTimeout(int timeout)This method is used to set the time out value for server. This is the time that server socket takes to wait for client request to be accepted.
ServerSocket Class Methods

The below example shows how to create networks in java programming language. The first program is for client side and the other program is for client side java networking.

// The File Name is ClientConnection.java
import java.net.*;
import java.io.*;

public class ClientConnection {

   public static void main(String [] args) {
      String server = args[0];
      int port = Integer.parseInt(args[1]);
      try {
         System.out.println("Establishing Connection to " + server + " on port " + port);
         Socket client = new Socket(server, port);
         
         System.out.println("Successfully 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 greets " + in.readUTF());
         client.close();
      } catch (IOException e) {
         e.printStackTrace();
      }
   }
}

The above code is used to connect client to a server by using a socket. It sends a greeting message and waits for a response from server.

// The File Name is ServerConnection.java
import java.net.*;
import java.io.*;

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

   public void run() {
      while(true) {
         try {
            System.out.println("Waiting for client connection on port " + 
               serverSocket.getLocalPort() + "...");
            Socket server = serverSocket.accept();
            
            System.out.println("Successfully 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 establishing connection 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 ServerConnection(port);
         t.start();
      } catch (IOException e) {
         e.printStackTrace();
      }
   }
}

The output of the above codes after compilation and execution is :