This tutorial will provide you with a detailed understanding of how a TCP client is built using Java. Also, several of the concepts of Java clients will be explained.

In order to build a TCP client in Java the basics of Java must first be learned. This can be done by reading a Java book aimed at beginners. I have several recommendations for such literature in order from 1 to 3, 1 being my personal favourite and 3 being my least favourite, including:

  1. Java For Dummies (http://www.amazon.com/Java-Dummies-Aaron-Walsh/dp/156884641X)
  2. Java All In One Desk Reference For Dummies (http://www.amazon.com/Java-All-One-Reference-Dummies/dp/076458961X)
  3. Beginning Programming  with Java For Dummies (http://www.amazon.com/Beginning-Programming-Java-Dummies-Barry/dp/0764588745)

 

The above list of books is current at the time of writing. However, I take no responsibility for the availability of these books in the future.

 

Below is the source code for the most recent revision of the first Java client I ever wrote. So it is very unlikely that there will be any bugs.

package client;

/*
* @author Dillon Chaffey
* Website: https://chafflube.wordpress.com
* E-mail: chafflube@hotmail.com
*/

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

public class Client {
    static String hostString = "127.0.0.1";     // Modify this value (127.0.0.1) to the IP address you want your client to connect to (the server’s IP address)
    static int portInt = 45454;                            // Modify this value (45454) to the port number that the server is accepting connections on
    static Socket connectionSocket = null;
    static PrintWriter out = null;
    static BufferedReader in = null;
    static String fromUserString = null;
    static String fromServer = null;
    static BufferedReader stdIn = null;
    static String hostInetAddressString = null;  

    public static void main(String[] args) {
        try {
            connectionSocket = new Socket(hostString, portInt);
            hostString = connectionSocket.getInetAddress().toString();
            out = new PrintWriter(connectionSocket.getOutputStream(), true);
            in = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
            // Get the Inet Address of the connectionSocket and store it in the hostInetAddress InetAddress variable and then cast the hostInetAddress to a String named hostInetAddressString
            hostInetAddressString = connectionSocket.getInetAddress().toString();
            System.out.println("Connected to server with Inet Address " + hostInetAddressString + " on port: " + connectionSocket.getPort() + "\n");
        }
        catch (Exception e) {
            System.err.println(e);
            System.exit(1);
        }
       

        // This is used to allow the client to receive input based on the program’s user pressing keys on their keyboard
        stdIn = new BufferedReader(new InputStreamReader(System.in));

        while (true) {
            try {
                if (fromUserString != null) {
                    out.println(fromUserString);
                    fromUserString = null;
                }   
            }
            catch (Exception e) {
                System.err.println(e);
                break;
            }
        }
    }
   
    public void closeClient() {
        // Try to close printers, writers and then sockets if it fails catch an exception
        try {
            out.close();
            in.close();
            stdIn.close();
            connectionSocket.close();
        }
        catch (Exception e) {
            System.err.println(e);
        }       
    }
}

 

The above code may be hard to read due to the fact that it is so heavily commented. The reason that it is commented so heavily is so that beginner users of Java are able to more easily gain an understanding of the code. If the code does not make any sense whatsoever then it is more than likely within your best interests to read one of the aforementioned beginner Java books and experiment with the code within the books and rework them to suit real life situations, as by doing so you are bound to learn faster than simply reading the books and neglecting to practice writing actual code. A good thing to do is write a program in “pseudo-code,” which is writing a program in English rather than actual code and it should give an overall view of the program you wish to create. After you have done this you may then learn how to code your program one piece at a time. Eventually you will have a functional, useful program and you will have learned more about the Java programming language than simply reading a book.

 

Now that you have built your own client you will need a server in order to experiment with network communication. Fortunately there is a tutorial on this site that shows you exactly how you can do this. The link to this tutorial is below:

https://chafflube.wordpress.com/2012/01/16/how-to-build-a-tcp-server-in-java/

I hope that this tutorial has helped you on your journey to learning the Java programming language. Java is arguably the best platform for network software development. So by creating clients and servers in Java you are making a very efficient use of such a fast-moving, powerful language.

Advertisements