import java.io.*; import java.net.*; /* ******************************************************************* Bert G. Wachsmuth June 3, 1996 Part of JokeServer: This JokeHandler thread understands the following commands: get: server sends a knock-knock joke bye: server closes thread for a connection, waits for next one shutdown: server shuts down completely, no more connections possible The thread waits for a new connection, serves it, and waits for next connection ******************************************************************* */ class JokeHandler extends Thread { private static int thePort = 4444; private static final int NUMJOKES = 5; private String clues[] = { "Turnip", "Little Old Lady", "Atch", "Who", "Who" }; private String answers[] = {"Turnip the heat, it's cold in here!", "I didn't know you could yodel!", "Bless you!", "Is there an owl in here?", "Is there an echo in here?" }; private String inputLine; private ServerSocket serverSocket = null; /* ******************************************************************* */ JokeHandler() { super("JokeServer"); try { serverSocket = new ServerSocket(thePort); System.out.println("Server started at port " + thePort); } catch (IOException e) { System.out.println("Port " + thePort + " unavailable: " + e); System.exit(1); } } /* ******************************************************************* */ public void run() { if (serverSocket == null) return; while (true) { Socket clientSocket = null; try { clientSocket = serverSocket.accept(); System.out.println("New Connection accepted"); } catch (IOException e) { System.out.println("Accept failed: " + thePort + ", " + e); System.exit(1); } try { DataInputStream inStream = new DataInputStream( new BufferedInputStream(clientSocket.getInputStream())); PrintStream outStream = new PrintStream( new BufferedOutputStream(clientSocket.getOutputStream(), 1024), false); outStream.println("JokerServer ready"); outStream.flush(); while ((inputLine = inStream.readLine()) != null) { if (inputLine.equalsIgnoreCase("Get")) ServeJoke(outStream); else if (inputLine.equalsIgnoreCase("Bye")) break; if (inputLine.equalsIgnoreCase("Shutdown")) System.exit(0); } outStream.close(); inStream.close(); clientSocket.close(); } catch (IOException e) { e.printStackTrace(); } } } /* ******************************************************************* */ protected void finalize() { if (serverSocket != null) { try { serverSocket.close(); } catch (IOException e) { e.printStackTrace(); } serverSocket = null; } } /* ******************************************************************* */ private void ServeJoke(PrintStream outStream) { int currentJoke = (int)(Math.random() * NUMJOKES); outStream.println(clues[currentJoke]); outStream.flush(); outStream.println(answers[currentJoke]); outStream.flush(); } /* ******************************************************************* */ }