65.9K
CodeProject is changing. Read more.
Home

Using Sockets in Java - Client

starIconstarIconstarIconstarIconemptyStarIcon

4.00/5 (5 votes)

Mar 24, 2008

CPOL

2 min read

viewsIcon

46535

downloadIcon

926

Creating a client program using Java.

Introduction

In this article, I will demonstrate how to create a client program using Java. This article is the continuation of my previous article about creating a server program. To understand this article, I recommend that you have already read the first one: Using Sockets in Java - Server.

Using the code

This code is very similar to the server code. To create a client, you need to follow only four steps:

  1. Establish a connection to the server.
  2. Set up input and output streams.
  3. Send and receive data.
  4. Close the connection.

Let's take the first step:

  1. We have to create a Socket object, by supplying its constructor with the following arguments:
    • the server's IP address (this is the Inet address)
    • the appropriate port number for the service

    The port number for the server and client programs must be the same, of course!

    To be more easy, we will place the client and the server on the same host, which will allow us to retrieve the IP address by calling the static method getLocalHost of the class InetAddress.

    Socket link = new Socket(InetAddress.getLocalHost(), 1234);
  2. These are set up in exactly the same way as the server streams are set up (by calling the methods getInputStream and getOutputStream of the Socket object that was created in step 2 in the previous article: Using Sockets in Java - Server).
  3. The Scanner object at the client end will receive messages sent by the PrintWriter object at the server end, while the PrintWriter object at the client end will send messages that are received by the Scanner object at the server end (using the methods nextLine and println).
  4. This is exactly the same as for the server process:
  5. link.close();

The code

Here is the complete code:

import java.io.*;
import java.net.*;
import java.util.*;

public class TCPEchoClient
{
    private static InetAddress host;
    private static final int PORT = 1234;

    public static void main(String[] args)
    {
        try
        {
            host = InetAddress.getLocalHost();
        }
        catch(UnknownHostException uhEx)
        {
            System.out.println("Host ID not found!");
            System.exit(1);
        }
        accessServer();
    }

    private static void accessServer()
    {
        Socket link = null;      //Step 1.

        try
        {
            link = new Socket(host,PORT); //Step 1.

            Scanner input = new Scanner(link.getInputStream());//Step 2.

            PrintWriter output =
                new PrintWriter(link.getOutputStream(),true);//Step 2.

            //Set up stream for keyboard entry...
            Scanner userEntry = new Scanner(System.in);

            String message, response;
            do
            {
                System.out.print("Enter message: ");
                message =  userEntry.nextLine();
                output.println(message);        //Step 3.
                response = input.nextLine();    //Step 3.
                System.out.println("\nSERVER> " + response);
            }while (!message.equals("***CLOSE***"));
        }
        catch(IOException ioEx)
        {
            ioEx.printStackTrace();
        }

        finally
        {
            try
            {
                System.out.println("\n* Closing connection... *");
                link.close();                    //Step 4.
            }
            catch(IOException ioEx)
            {
                System.out.println("Unable to disconnect!");
                System.exit(1);
            }
        }
    }
}

For more information or for any kind of clarifications, please don't hesitate to contact me: mihailescu.marius@yahoo.com. Until then, I wish you all Happy Coding!