71 static final byte[] requestEnd = new byte[] {'\r', '\n', '\r', '\n' }; |
71 static final byte[] requestEnd = new byte[] {'\r', '\n', '\r', '\n' }; |
72 |
72 |
73 // Read until the end of a HTTP request |
73 // Read until the end of a HTTP request |
74 void readOneRequest(InputStream is) throws IOException { |
74 void readOneRequest(InputStream is) throws IOException { |
75 int requestEndCount = 0, r; |
75 int requestEndCount = 0, r; |
|
76 StringBuilder sb = new StringBuilder(); |
76 while ((r = is.read()) != -1) { |
77 while ((r = is.read()) != -1) { |
|
78 sb.append((char)r); |
77 if (r == requestEnd[requestEndCount]) { |
79 if (r == requestEnd[requestEndCount]) { |
78 requestEndCount++; |
80 requestEndCount++; |
79 if (requestEndCount == 4) { |
81 if (requestEndCount == 4) { |
80 break; |
82 break; |
81 } |
83 } |
82 } else { |
84 } else { |
83 requestEndCount = 0; |
85 requestEndCount = 0; |
84 } |
86 } |
85 } |
87 } |
|
88 System.out.println("Server got request: " + sb.toString()); |
86 } |
89 } |
87 |
90 |
88 public void run() { |
91 public void run() { |
89 try { |
92 try { |
90 readyToStart.countDown(); |
93 readyToStart.countDown(); |
91 for (int i=0; i<NUM_REDIRECTS; i++) { |
94 for (int i=0; i<NUM_REDIRECTS; i++) { |
92 try (Socket s = ss.accept()) { |
95 try (Socket s = ss.accept()) { |
|
96 System.out.println("Server accepted socket: " + s); |
93 s.setSoTimeout(TIMEOUT); |
97 s.setSoTimeout(TIMEOUT); |
94 readOneRequest(s.getInputStream()); |
98 readOneRequest(s.getInputStream()); |
|
99 System.out.println("Redirecting to: /redirect" + i); |
95 String reply = reply1 + port + "/redirect" + i + reply2; |
100 String reply = reply1 + port + "/redirect" + i + reply2; |
96 s.getOutputStream().write(reply.getBytes()); |
101 s.getOutputStream().write(reply.getBytes()); |
97 } |
102 } |
98 } |
103 } |
99 try (Socket s = ss.accept()) { |
104 try (Socket s = ss.accept()) { |
|
105 System.out.println("Server accepted socket: " + s); |
100 s.setSoTimeout(TIMEOUT); |
106 s.setSoTimeout(TIMEOUT); |
101 readOneRequest(s.getInputStream()); |
107 readOneRequest(s.getInputStream()); |
|
108 System.out.println("Replying..."); |
102 s.getOutputStream().write(reply3.getBytes()); |
109 s.getOutputStream().write(reply3.getBytes()); |
103 } |
110 } |
104 } catch (Exception e) { |
111 } catch (Exception e) { |
105 e.printStackTrace(); |
112 e.printStackTrace(); |
106 } |
113 } |