1 20 package org.apache.mina.example.httpserver.stream; 21 22 import java.io.BufferedReader ; 23 import java.io.BufferedWriter ; 24 import java.io.IOException ; 25 import java.io.InputStream ; 26 import java.io.InputStreamReader ; 27 import java.io.OutputStream ; 28 import java.io.OutputStreamWriter ; 29 import java.io.PrintWriter ; 30 import java.util.Iterator ; 31 import java.util.Map ; 32 import java.util.TreeMap ; 33 import java.util.Map.Entry; 34 35 import org.apache.mina.common.IoSession; 36 import org.apache.mina.handler.StreamIoHandler; 37 38 45 public class HttpProtocolHandler extends StreamIoHandler { 46 protected void processStreamIo(IoSession session, InputStream in, 47 OutputStream out) { 48 new Worker(in, out).start(); 50 } 51 52 private static class Worker extends Thread { 53 private final InputStream in; 54 55 private final OutputStream out; 56 57 public Worker(InputStream in, OutputStream out) { 58 setDaemon(true); 59 this.in = in; 60 this.out = out; 61 } 62 63 public void run() { 64 String url; 65 Map <String , String > headers = new TreeMap <String , String >(); 66 BufferedReader in = new BufferedReader (new InputStreamReader ( 67 this.in)); 68 PrintWriter out = new PrintWriter (new BufferedWriter ( 69 new OutputStreamWriter (this.out))); 70 71 try { 72 url = in.readLine().split(" ")[1]; 74 75 String line; 77 while ((line = in.readLine()) != null && !line.equals("")) { 78 String [] tokens = line.split(": "); 79 headers.put(tokens[0], tokens[1]); 80 } 81 82 out.println("HTTP/1.0 200 OK"); 84 out.println("Content-Type: text/html"); 85 out.println("Server: MINA Example"); 86 out.println(); 87 88 out.println("<html><head></head><body>"); 90 out.println("<h3>Request Summary for: " + url + "</h3>"); 91 out 92 .println("<table border=\"1\"><tr><th>Key</th><th>Value</th></tr>"); 93 94 Iterator it = headers.entrySet().iterator(); 95 while (it.hasNext()) { 96 Entry e = (Entry) it.next(); 97 out.println("<tr><td>" + e.getKey() + "</td><td>" 98 + e.getValue() + "</td></tr>"); 99 } 100 101 out.println("</table>"); 102 103 for (int i = 0; i < 1024; i++) { 104 out.println("this is line: " + i + "<br/>"); 105 } 106 107 out.println("</body></html>"); 108 } catch (Exception e) { 109 e.printStackTrace(); 110 } finally { 111 out.flush(); 112 out.close(); 113 try { 114 in.close(); 115 } catch (IOException e) { 116 } 117 } 118 } 119 } 120 } 121 | Popular Tags |