ServerSocket & Socket Part 1 Tutorial

This tutorial will continue expanding on concepts from my ServerSocket & Socket Introduction. I am going to create a server socket prime number calculator application that communicates over port 4141. The server socket will listen for the incoming client connections to provide a number, then the server will respond back with PRIME, COMPOSITE, or Invalid number. In addition to that I am going to throw in a little bonus knowledge on how part of the underlying Transmission Control Protocol/Internet Protocol (TCP/IP) actually functions. TCP was created way back in the 70's and has slowly evolved into the dominant method of transferring data. There are three things that I am going to go over in this video:

  • SYN - synchronize
  • ACK - acknowledge
  • FIN - final
They form the basis for both establishing socket communications and terminating socket communications. Let's get started...



Open the command prompt (CMD - see the Getting Started ) and type in the following commands.

C:\Windows\System32>cd \
C:\>md Java
C:\>cd Java
C:\Java>
C:\Java>md SocketOne
C:\Java>cd SocketOne
C:\Java\SocketOne>Notepad Server.java

Copy and Paste, or type the following code into Notepad and be sure to save the file when you are done.


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

public class Server {
    public static void main(String[] args){
        Server server = new Server();
        try(ServerSocket serverSocket = new ServerSocket(4141)) {
            while (true) {
                System.out.println("Listening on port 4141, CRTL-C to quit ");
                Socket socket = serverSocket.accept();
                try ( 	PrintWriter output = new PrintWriter(socket.getOutputStream(), true);
                        BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                ){
                    System.out.println("Connection accepted.");
                    String in = "";
                    while ((in = input.readLine()) != null) {
                        System.out.println("Received: " + in);
                        if (in.equals("SYN")){ // Synchronize
                            server.write(output, "SYN-ACK"); // Synchronize-Acknowledge
                        }	
                        if (in.equals("FIN")){ // Final
                            server.write(output, "FIN-ACK"); // Final-Acknowledge
                            break;
                        }
                        if (in.contains("number=")){
                            server.write(output, server.calcPrime(in));
                        }				
                    }
                    System.out.print("Closing socket.\n\n");				
                } catch (IOException e) {
                    e.printStackTrace();	
                } 
            } 
        } catch (IOException e) {
            e.printStackTrace();	
        }
    }

    void write(PrintWriter output, String message) {
        System.out.println("Sending: "+message);
        output.println(message);
    }

    String calcPrime(String input) {
        int i = 0;
        try {
            i = Integer.parseInt(input.substring(7));
            int x = 2;
            while(x < i){
                if (i % x == 0) {
                    return "answer=COMPOSITE";
                }
                x++;
            }
        } catch (NumberFormatException e) {
            return ("answer=INVALID NUMBER");
        }
        return "answer=PRIME";
    }
}

Now switch back to the command prompt (CMD) and type in javac SocketOne.java and press Enter.
Now type in java SocketOne and press Enter.


C:\Java\SocketOne>javac Server.java
C:\Java\SocketOne>java Server

Type in the following commands into a new dos prompt on the Java\SocketOne folder.


C:\Java\SocketOne>Notepad Client.java

Copy and Paste, or type the following code into Notepad and be sure to save the file when you are done.


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

class Client {
    public static void main(String[] args) {
        if (args.length != 1) {
            System.out.println("Must include a number as a command line argument, please try again.");
            return;
        }
	
        Client client = new Client();
        // change the IP address to your server's ip address
        try (   Socket socket = new Socket(InetAddress.getByName("10.0.0.183"), 4141); 
            PrintWriter output = new PrintWriter(socket.getOutputStream(), true);
            BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        ) { 	
            client.write(output, "SYN"); // Synchronize
            String in = "";
            while ((in = input.readLine()) != null) {
                System.out.println("Received: " + in);
                if (in.equals("SYN-ACK")){ // Synchronize-Acknowledge
                    client.write(output, "ACK");
                    client.write(output, "number="+args[0]);
                }
                if (in.equals("FIN-ACK")){ // Final-Acknowledge
                    break;
                }
                if (in.contains("answer=")){ 
                    client.write(output, "FIN");
                }
            }
            System.out.print("Closing socket.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    void write(PrintWriter output, String message) {
        System.out.println("Sending: " +message);
        output.println(message);
    }
}

Now switch back to the command prompt (CMD) and type in javac SocketOne.java and press Enter.
Now type in java SocketOne and press Enter.


C:\Java\SocketOne>javac Client.java
C:\Java\SocketOne>java Client
See Video

Final thoughts

None


Tutorials