1 package com.quadcap.http.server22; 2 3 40 41 import java.io.*; 42 import java.net.Socket ; 43 44 import com.quadcap.util.Debug; 45 import com.quadcap.util.Util; 46 47 52 public class Test extends com.quadcap.util.Test { 53 public Test() { 54 super(); 55 } 56 57 static byte[] delims = { 0x0d, 0x0a, 0x0d, 0x0a }; 58 59 public static byte[] readStream(InputStream is) throws IOException { 60 ByteArrayOutputStream bos = new ByteArrayOutputStream(); 61 62 int state = 4; 63 int cnt = 0; 64 while (state < 4) { 65 int c = is.read(); 66 if (c < 0) { 67 throw new IOException("unexpected eof in message headers"); 68 } 69 if (delims[state] == c) state++; 70 else if (delims[0] == c) state = 1; 71 else state = 0; 72 } 73 74 byte[] buf = new byte[1024]; 75 while ((cnt = is.read(buf)) > 0) { 76 bos.write(buf, 0, cnt); 77 } 78 return bos.toByteArray(); 79 } 80 81 public static byte[] fetch(String url) throws Exception { 82 Debug.println(3, "Fetch: " + url); 83 if (url.indexOf("http://") != 0) { 84 System.err.println("Bad url (protocol): " + url); 85 return null; 86 } 87 url = url.substring(7); 88 int idx = url.indexOf('/'); 89 if (idx <= 0) { 90 System.err.println("Bad url (host): " + url); 91 return null; 92 } 93 String host = url.substring(0, idx); 94 String name = url.substring(idx); 95 idx = host.indexOf(':'); 96 int port = 80; 97 if (idx >= 0) { 98 port = Integer.parseInt(host.substring(idx+1)); 99 host = host.substring(0, idx); 100 } 101 Socket s = new Socket (host, port); 102 103 OutputStream os = s.getOutputStream(); 104 BufferedOutputStream bos = new BufferedOutputStream(os); 105 106 bos.write(("GET " + name + " HTTP/1.0\r\n\r\n").getBytes()); 107 bos.flush(); 108 109 InputStream is = s.getInputStream(); 110 BufferedInputStream bis = new BufferedInputStream(is); 111 byte[] doc = readStream(bis); 112 os.close(); 113 is.close(); 114 s.close(); 115 return doc; 116 } 117 118 public void testFetch(String args[]) { 119 int cnt = Util.intProperty("count", 100); 120 String url = System.getProperty("url"); 121 if (cnt > 10) { 122 try { 123 fetch(url); 124 } catch (Exception e) { 125 Debug.print(e); 126 } 127 } 128 129 long start = System.currentTimeMillis(); 130 try { 131 for (int i = 0; i < cnt; i++) { 132 fetch(url); 133 } 134 } catch (Exception e) { 135 Debug.print(e); 136 } 137 long end = System.currentTimeMillis(); 138 long elap = end - start; 139 double fps = ((double)cnt) / (((double)elap) / 1000.0); 140 141 System.out.println("elapsed: " + (end - start) + " ms, " + 142 fps + " pages/sec"); 143 } 144 145 146 public static void main(String args[]) { 147 Test test = new Test(); 148 test.test(args); 149 } 150 } 151 | Popular Tags |