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:
- Establish a connection to the server.
- Set up input and output streams.
- Send and receive data.
- Close the connection.
Let's take the first step:
- 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
Socket link = new Socket(InetAddress.getLocalHost(), 1234);
These are set up in exactly the same way as the server streams are set up (by calling the methods
getOutputStream of the
Socket object that was created in step 2 in the previous article: Using Sockets in Java - Server).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
println).This is exactly the same as for the server process:
Here is the complete code:
public class TCPEchoClient
private static InetAddress host;
private static final int PORT = 1234;
public static void main(String args)
host = InetAddress.getLocalHost();
System.out.println("Host ID not found!");
private static void accessServer()
Socket link = null;
link = new Socket(host,PORT);
Scanner input = new Scanner(link.getInputStream());
PrintWriter output =
Scanner userEntry = new Scanner(System.in);
String message, response;
System.out.print("Enter message: ");
message = userEntry.nextLine();
response = input.nextLine();
System.out.println("\nSERVER> " + response);
System.out.println("\n* Closing connection... *");
System.out.println("Unable to disconnect!");
For more information or for any kind of clarifications, please don't hesitate to contact me: email@example.com. Until then, I wish you all Happy Coding!