Title: Networking: Sample Protocol Handlers
Course: CPS 261: Advanced Java Concepts ~ DL & MM MASTER

Networking: Sample Protocol Handlers

Note that in the notes I added "public" to the overridden methods processNextLine and processStream. This wasn't in the video because I made some changes since the video that requires the "public" attribute. One other difference in the video is that the ConnectionListener Interface was eliminated for simplicity.

Rock Paper Scissors Protocol

Here is our first example of another protocol handler that will make use of the EchoServer class features.

Note that the EchoServer class code will all be used except for the "processNextLine" method which we are overriding

RPS Game:

- You pick one of { r, p, s} for Rock Paper Scissors. Normally you play this against another player who does the same thing.
- In our case, the computer will generate the other players choice on {r,p, s}
- Results:
  - If both players pick the same thing, the game is a tie
  - Rock beats Scissors ( Rock breaks Scissors)
  - Scissors beats paper (Scissors can cut paper)
  - Paper beats Rock (Paper can cover Rock .... I never quit understood this logic??????)

RPS_Server.java


import java.io.PrintStream;
import java.util.Scanner;

public class RPS_Server extends EchoServer{
    static final char paper ='p';
    static final char rock = 'r';
    static final char scissors ='s';

//Overriding from EchoServer
    public void processNextLine(Scanner input, PrintStream ps)
    {
        String s= input.nextLine().toLowerCase();
        if (s.length() == 0)
        {
            ps.println("Enter r,p,s for Rock, Paper, Scissors");
            return;
        }

        char clientChoice= s.charAt(0);
        char computerChoice = computerPick();

        System.out.println("You: "+ clientChoice+ " Computer: "+ computerChoice);
        String response = "You: " + rps_results(clientChoice,  computerChoice);

        ps.println(response);
        System.out.println("EchoServer echoed: "+response);
    }

    private char computerPick()
    {
        switch((int)(3* Math.random()))
        {
        case 0:
            return scissors;
        case 1:
            return paper;
        case 2:
            return rock;
        }
        return '?'; // Bad input and shouldn't happen
    }

    String rps_results(char userInput,  char otherInput)
    {
        String response=" LOSE :-) !!";

        if ( userInput == otherInput)
        {
            response =  " Tied";
        }
        else
        {
            switch (userInput)
            {
            case scissors:
                if (otherInput == paper)
                    response= " WIN!!";
                break;
            case rock:
                if (otherInput == scissors)
                    response =  " WIN!!";
                break;
            case paper:
                if (otherInput == rock)
                    response = " WIN!!";
                break;
            default:
                response = " had bad input: " +userInput +
                            " -- Enter r,p,s for Rock, Paper, Scissors";
            }
        }
        return response;
    }

    public static void main(String[] args) {
        RPS_Server es = new RPS_Server();
        es.monitorServer();
        System.out.println("Exitting RPS_Server");

    }

}



Simple Http Server

- We will use EchoServer to make a simplified Http Server. For the sake of simplicity, we are only trying to respond to a very small subset of http functionality.
- However, there is nothing to prevent you from enhancing this into a full fledged Http Server if you wanted to. Not sure what you would do with it except that it would be a fun learning experience.
- This time we will override the processStream method to give us more options on what we can do.
- To use this code:
  - Put some html files at the Project level of your Project: I will be using the files home.html, like.html, gettysburg.html
  - My client will be a browser. Let hostName be the IpAddress of your HttpServer. If your server is running on the same machine as your browser, then you can use hostName=localhost
  - Assuming that your host is still using my default port number of 4444, then the possible URLs for this HttpServer are:
    - hostName:4444
    - hostName:4444/home.html
    - hostName:4444/like.html
    - hostName:4444/gettysburg.html - Note that when you run this, you will see some errors show up on the Server side, because the browser will be requesting some image files which don't exist. Also I haven't provided the code to deal with images. It's not difficult, but it is more than I want to do in this example.

HttpServer.java


import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.Scanner;
import java.util.StringTokenizer;

public class HttpServer extends EchoServer{
    // Overriding processStream from EchoServer

    public void processStream(InputStream is, OutputStream os)
    {
        System.out.println("HttpServer.processStream begins");

        PrintStream ps = new PrintStream(os);
        BufferedReader input = new BufferedReader(new InputStreamReader(is));

        String cmd;
        try
        {
            // We are only looking at GET requests:
            // We will be looking for something like:
            // GET /like.html HTTP/1.1

            cmd= input.readLine(); // We are only looking at the first line
            System.out.println(cmd);
            StringTokenizer parse = null;
            if (cmd != null)
                parse = new StringTokenizer(cmd);
            String fileName="home.html";
            if (parse!= null && parse.countTokens() >= 2)
            {
                String method = parse.nextToken();  // Should contain GET
                String tempFileName=parse.nextToken().trim();         // Could contain a filename
             // We expect either "/"  or "/someFileName"
                if (!tempFileName.equals("/"))
                    fileName = tempFileName.substring(1); // strip off leading "/"

                System.out.println("method="+method);
                System.out.println("fileName="+fileName);
            }


            ps.println("HTTP/1.1 200 OK");
            ps.println("content-type: text/html");

// This blank line says we are done with HTTP headers and ready to send the data
            ps.println();

// Send out our html file to the browser
            File f = new File(fileName);
            Scanner readIt = new Scanner(f);
            while (readIt.hasNextLine())
            {
                String s = readIt.nextLine();
                ps.println(s);
            }
// closing the TCP/IP connection tells the browser we are done.
            input.close();
            ps.close();
            is.close();
            os.close();
        }
        catch (IOException e)
        {
            System.out.println("HttpServer.processStream IOException: "+e);
        }
        System.out.println("Exitting processStream");
    }
    public static void main(String[] args) {
        HttpServer es = new HttpServer();
        es.monitorServer();
        System.out.println("Exitting HttpServer");

    }

}



Last Modified: September 6, 2015 10:27 PM