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

In order to build a TCP server 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. Although, these books are of such high quality for the Java beginner that I believe anybody would find great difficulty in discontinuing them.

 

Below is the source code for one of the first TCP servers I have built in Java. Don’t be fooled by the fact that it was one of the first I built as since I have built it I have used it as a base for many of my programs requiring a reliable TCP network connection and this code is the most recent at the time of writing of my revisions.

package server;

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

public class Server { 
    // Below are variable declarations. They are given the static modifier as they need to be used within a static context (the main() method)
    static String hostInetAddressString;
    static String clientInetAddressString;
    static int clientPortInt;
    static ServerSocket serverSocket = null;
    static Socket clientSocket = null;
    static int clientSocketReceiveBufferSizeInt;
    static int clientSocketSendBufferSizeInt;
    static BufferedReader stdIn;
    static String fromUserString;
    static PrintWriter out;
    static BufferedReader in;
    static int portInt;
    static String fromClient;
   
    // The main() method of the server program (body of the program)
    public static void main (String[] args) {
        portInt = 45454; // Change this value to determine which port the server will start one and can be accessed through using a client
        // These two variables are used to set the receive and send buffer size of the clientSocket when a client connects
        // A lower value (2-4) will generally increase the performance of a connection frequently transferring small amounts of data (i.e. short text strings)
        // A higher value (4-16) will generally increase the performance of a connection frequently transferring large amounts of data (i.e. file transfer)
        clientSocketReceiveBufferSizeInt = 2;
        clientSocketSendBufferSizeInt = 2;
        // Alert server user that the server is initiating
        System.out.println("Server is intitiating. Please wait…");

        try {
            serverSocket = new ServerSocket(portInt);
            hostInetAddressString = serverSocket.getInetAddress().toString();
        }
        catch (IOException e) {
            System.out.println("Could not listen on port: " + portInt);
            System.exit(1);
        }
            // Alert server user that the server is now ready to accept incoming connection requests
            System.out.println("Server initiated. Awaiting connection request…\n");

        try {
            clientSocket = serverSocket.accept();
            // Get the Inet Address of the clientSocket and store it in the clientInetAddress InetAddress variable and then cast the clientInetAddress variable to a String named clientInetAddressString
            clientInetAddressString = clientSocket.getInetAddress().toString();
            // Set the receive buffer size of the clientSocket to that set in the int variable clientSocketReceiveBufferSizeInt
            clientSocket.setReceiveBufferSize(clientSocketReceiveBufferSizeInt);
            // Set the send buffer size of the clientSocket to that set in the int variable clientSocketSendBufferSizeInt
            clientSocket.setSendBufferSize(clientSocketSendBufferSizeInt);
            // Alert the server user that they are connected to the server and give them some details of the connection
            System.out.println("Client connected with Inet Address " + clientInetAddressString + " on port: " + clientSocket.getPort() + "\n");
        }
        catch (IOException e) {
            System.err.println(e);
            System.exit(1);
        }

        try {
            out = new PrintWriter(clientSocket.getOutputStream(), true);
            in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        }
        catch (Exception e) {
            System.err.println(e);
        }

        while (true) {
            try {
                if ((fromClient = in.readLine()) != null) {
                    System.out.println("Client: " + fromClient + "\n");   
                }
                else {
                    //break;
                }
            }
            catch (IOException ioe) {
                System.err.println(ioe);
                closeServer();
            }
        }
    }
   
    public static void closeServer() {
        // Close writers, readers and then sockets
        try {
            out.close();
            in.close();
            clientSocket.close();
            serverSocket.close();
            System.exit(0);
        }
        catch (Exception e) {
            System.err.println(e);
        }
    }
}

 

The above code is commented as to allow a Java programmer who has read one or more of the aforementioned books to understand the code at least partially if not fully. However, if you have not yet invested the time to read one of those books, the code will probably not make much sense. Although even if you have not yet read any of the books, you have no reason to be concerned as the Java For Dummies book can be read through in just a few hours a day for 2-4 days and that is for an average speed reader (such as myself). So if you are a fast reader much less time will be required.

 

Now that you have built your own server the next step is to build a client so that you can experiment with network programming in Java. Luckily for you there is a tutorial on this site that will tell you how to do just that. The link to the tutorial is below:

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

Hopefully you can learn from this code and ultimately understand it and incorporate it into your future Java programs. Good luck with your adventure learning and using Java and who knows, you might just make a hobby out of it.

Advertisements