TCP Socket Client Program

Below is TCP Socket client program.
Step 1: import required packages java.net and java.io
Step 2: Use Socket(with Server IP Address and port number) class to connect to Server Program.
Step 3: Write data to Server Program
Step 4: Read response String from Server
Step 5: Print response from Server

TCP Socket example
TCP Socket example

Click here for step by step Java Server Program

//step 1
import java.net.*;
import java.io.*;

public class HelloClient
{
   public static void main(String [] args)
   {
      String serverName = "localhost";
      //"localhost" can b replaced with Loopback IP addr 127.0.0.1,
      //if server program is on same machine as client

      //If server is locate on some other machine, pls specify it's IP address, above
      int port = 6066;
      try
      {
         //step 2
         System.out.println("Client: Connecting to (Server) " + serverName +
		 " on port number " + port);
         Socket client = new Socket(serverName, port);
         System.out.println("Client: Just connected to (Server) "
		 + client.getRemoteSocketAddress());
         OutputStream outToServer = client.getOutputStream();

         //step 3
         DataOutputStream out = new DataOutputStream(outToServer);
         out.writeUTF("[From Client]Request from "
                      + client.getLocalSocketAddress());
         InputStream inFromServer = client.getInputStream();

         //step 4
         DataInputStream in =
                        new DataInputStream(inFromServer);

         //step 5
         System.out.println("Client: Response on Server " + in.readUTF());
         client.close();
      }
      catch(MalformedURLException me)
      {
          me.printStackTrace();
      }
      catch(IOException e)
      {
         e.printStackTrace();
      }
   }
}

You may also like to read:
ServerSocket Program
How to use IPv6 address in Java
How remote objects can interact in Java

TCP ServerSocket Program

Below is Server program, based on TCP/IP. For details on TCP, please read Java Networking
Step 1.import java.net and java.io packages
Step 2.Create ServerSocket Listening on a port
Step 3.Waits for 65000 milliseconds for request from any client. On receiving a request from client, read request from client
Step 4.Print client request on server console
Step 5.Now send response to client program.

SocketServer Example
SocketServer example

Using Thread for a server is not mandatory, and can be used for better performance, if required

//step 1
import java.net.*;
import java.io.*;

public class HelloServer extends Thread
{
   private ServerSocket server_obj;

   public HelloServer(int port) throws IOException
   {
     //step 2, Create ServerSocket and listen on a port
      server_obj = new ServerSocket(port, 5);//5 is number of back log requests

      //waits for 65000 milliseconds to receive request from client
      //If no request is received from client within 65000, SocketTimeoutException is thrown
      server_obj.setSoTimeout(65000);
   }

   public void run()
   {
    for(;;) //infinite for loop
    {
    try
    {
       System.out.println("Server: ..Waiting for client request on port number " +
       server_obj.getLocalPort() );
       //step 3
       Socket server = server_obj.accept();
       System.out.println("Server: Connecting to client with IP addr "
             + server.getRemoteSocketAddress());
       DataInputStream in =
             new DataInputStream(server.getInputStream());
       //step 4
       System.out.println(in.readUTF());

       //step 5
       DataOutputStream out =
            new DataOutputStream(server.getOutputStream());
       out.writeUTF("[From Server] This message is from server "
         + server.getLocalSocketAddress() + " Thanks for your request");
       server.close();
    }
    catch(SocketTimeoutException s)
    {
       System.out.println("Server: SocketTimeoutException occurred");
       s.printStackTrace();
       break;
    }
    catch(Exception ep)
    {
       System.out.println("Server: Exception occurred");
       ep.printStackTrace();
       break;
    }
    }
   }
   public static void main(String [] args)
   {
       //port number on which server is listening
       //clients need to send request to this port number
      int port_number = 6066;
      try
      {
         Thread t = new HelloServer(port_number);
         t.start();
      }catch(IOException e)
      {
         e.printStackTrace();
      }
   }
}

You may also like to read:
Step by Step Socket Client Program
What is Remote Method Invocation?
Where does printStackTrace() print to?
Can I create Child Thread to another Child Thread?

Remote Method Invocation in Java

RMI(Remote Method Invocation) is used to develop distributed Java Applications. Two or more Java objects located remotely can interact with each other, using RMI.
RMI uses Sockets internally for communication between client and server machines.

RMI Server

//Filename: Arith.java
//Step 1: interface need to extend from Remote interface
//The Remote interface serves to identify interfaces whose methods may be invoked from a non-local virtual machine. //Only those methods specified in a "remote interface", an interface that extends java.rmi.Remote are available //remotely.
import java.rmi.*;
public interface Arith extends Remote{
public int add(int x,int y)throws RemoteException;
public int sub(int x,int y)throws RemoteException;
public int mul(int x,int y)throws RemoteException;
}

//Filename: ArithRemote.java
import java.rmi.*;
import java.rmi.server.*;
//Step 2: extend class from UnicastRemoteObject and implement from above Arith interface
//All the basic functionalities of RMI are actually implemented in UnicastRemoteObject class.
//UnicastRemoteObject class implements java.io.Serializable, hence does marshalling/unmarshalling
//objects
public class ArithRemote extends UnicastRemoteObject implements Arith{
ArithRemote()throws RemoteException{
}
public int add(int x,int y){return x+y;}

public int sub(int i, int j)
{
    return i-j;
}

public int mul(int x,int y)
{
    return x*y;
}
}


//Filename:MyServer.java
//
import java.rmi.*;
import java.rmi.registry.*;
public class MyServer{
public static void main(String args[]){
try{
Arith stub=new ArithRemote();

//below statement starts registry, to help clients to lookup
//5000 is port on which remote object is available for interaction
LocateRegistry.createRegistry(5000);

//register remote object(i..e stub) with a name
//client will access this remote object using this name
Naming.rebind("rmi://localhost:5000/test1",stub);


}catch(Exception e)
{
    System.out.println(e);
}
}
}

RMI Client

import java.rmi.*;
import java.net.MalformedURLException;

public class MyClient{
public static void main(String args[]){
try{
Arith stub=(Arith)Naming.lookup("rmi://localhost:5000/test1");
//returns Remote object


System.out.println("Added:"+stub.add(34,4));
System.out.println("Sub:"+stub.sub(34,4));
System.out.println("Mul:"+stub.mul(34,4));
}catch(RemoteException e)
{
    System.out.println("RemoteException"+e.getMessage());
}
catch(NotBoundException nbe)
{//NotBoundException is thrown, if test1 name is not binded on server
    System.out.println("NotBoundException"+nbe.getMessage());
}
catch(MalformedURLException mue)
{//MalformedURLException is thrown, if URL we have provided is not in proper format
    System.out.println("MalformedURLException"+mue.getMessage());
}
}
}

Limitations of RMI:
RMI can be used for interaction between Java objects only. RMI is not Language independent.

Web Services(RESTful or SOAP) can be used for interaction between components implemented in different Programming Languages(Eg. Java, PHP, .NET,etc…)

You may also like to read:
What is Serialization in Java?
purpose of transient keyword