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