Click here to Skip to main content
12,999,417 members (95,052 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as


14 bookmarked
Posted 24 Mar 2008

Using Sockets in Java - Client

Rate this:
Please Sign up or sign in to vote.
Creating a client program using Java.


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.util.*;

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

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

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

            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(;

            String message, response;
                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)

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

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


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Marius Iulian Mihailescu
Instructor / Trainer Lumina - The University of South-East Europe
Romania Romania
No Biography provided

You may also be interested in...

Comments and Discussions

GeneralMy vote of 4 Pin
Sami Rebeiz25-Feb-13 12:56
memberSami Rebeiz25-Feb-13 12:56 
GeneralMy vote of 5 Pin
Member 432084430-Sep-11 3:31
memberMember 432084430-Sep-11 3:31 
Questionnot work ??? Pin
Member 285760531-Jul-10 0:44
memberMember 285760531-Jul-10 0:44 
GeneralJava Sockets Articles - Great Work Pin
MrZaggy7-Aug-09 4:54
memberMrZaggy7-Aug-09 4:54 
Contray to some of the comments posted in response to the first part of this article (Using Sockets in Java - Server, found at:, I'd just like to say thanks for a nice, concise and informative article. Smile | :)

While it is true that Java is not the flavour of the week with regards to developing production applications, I MUST point out to these people that it is more often than not the weapon of choice when it comes to research and cross-platform work; at least all Uni's that I have been exposed to. The fact is, as a learning language, its hard to beat (we learn to work with C++ and Java at Uni here, and with that combination under your belt, its not too hard to jump between languages and pick them up pretty quick); as a research language, its right up there (a mate of mine is doing some INCREDIBLE research work with Java); as a prototyping language, its awesome (I'm knocking up an External Ballistics sim in Java, which can then easily be ported to C++, C#, PHP, etc)...

But back to Marius's articles - thanks! I'd never played with Java Sockets (only C# in recent history) and these articles are just perfect to get me upto speed on the Java implementation in a manner of minutes. Great example code too; code that just works... Smile | :)

Thanks Smile | :)

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.170624.1 | Last Updated 24 Mar 2008
Article Copyright 2008 by Marius Iulian Mihailescu
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid