TCP Socket Client Program

Below is TCP Socket client program.
Step 1: import required packages and
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

public class HelloClient
   public static void main(String [] args)
      String serverName = "localhost";
      //"localhost" can b replaced with Loopback IP addr,
      //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;
         //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());
      catch(MalformedURLException me)
      catch(IOException e)

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

2 thoughts on “TCP Socket Client Program”

Leave a Reply