// Proge: v6rguprogramm // Grupp: // Silver Salonen // Virgo Vardja // Kait-Kaarel Kamla import java.io.*; import java.net.*; import java.util.regex.*; public class Random { public static int Requests = 0; public static double RandSum = 0; // Loome serversocketi ja hakkame requeste handleerima, tehes igayhe tarbeks oma threadi public static void main(String[] args) throws IOException { ServerSocket ss = new ServerSocket(80); while (true) { new RndThread(ss.accept()); } } } class RndThread extends Thread { Socket mySock; String ReqLine; String Request = ""; String Response = "ok"; int maxrnd; int ourRnd; public RndThread(Socket inSock) { mySock = inSock; start(); } public void run() { try { PrintWriter valja = new PrintWriter(mySock.getOutputStream(), true); BufferedReader sisse = new BufferedReader( new InputStreamReader(mySock.getInputStream())); // Hakkame requesti lugema ReqLine = sisse.readLine(); while (!ReqLine.equals("")) { // Tegelikult huvitab meid HTTP pa"ringust vaid rida 'GET /midagi HTTP/midagi' if (ReqLine.startsWith("GET /")) { // Yritame matchida patternit... Pattern p = Pattern.compile("^GET /(.*?) .*"); Matcher m = p.matcher(ReqLine); // ... ja tekitame muutujasse 'Request' ainult soovitud urli. Request = m.replaceAll("$1"); // Kui urliks on 'QUIT' siis l6petame proge to"o" if (Request.compareTo("QUIT") == 0) System.exit(0); // Kui url on tyhi, siis seame maxrnd'iks 10 else if (Request.length() == 0) maxrnd = 10; // Vastasel juhul seame maxrnd'iks kysitud arvu else try { maxrnd = Integer.parseInt(Request); // Oops. Request ei olnudki arv. } catch (Exception e) { Response = "bad"; } } ReqLine = sisse.readLine(); } // Paistab, et saime teada sobiva piirarvu. Genereerime juhuarvu. if (Response.compareTo("ok") == 0) { valja.println("HTTP/1.1 200 OK"); valja.println("Server: Random v.1"); valja.println("Content-type: text/html"); valja.println(); ourRnd = (int) Math.round(Math.random() * maxrnd); // Lisame statistikasse Random.Requests++; Random.RandSum += ourRnd; valja.println("