fork download
  1. import java.io.BufferedReader;
  2. import java.io.IOException;
  3. import java.io.InputStream;
  4. import java.io.InputStreamReader;
  5. import java.io.OutputStream;
  6.  
  7. import java.net.HttpURLConnection;
  8. import java.net.InetSocketAddress;
  9.  
  10. import java.nio.channels.SocketChannel;
  11. import java.nio.charset.Charset;
  12.  
  13. import java.lang.reflect.Field;
  14.  
  15. import java.util.List;
  16.  
  17. import com.sun.net.httpserver.HttpExchange;
  18. import com.sun.net.httpserver.HttpHandler;
  19. import com.sun.net.httpserver.HttpServer;
  20.  
  21. class Handler implements HttpHandler {
  22. private static final Charset UTF8 = Charset.forName("utf-8");
  23.  
  24. public void handle(final HttpExchange exchange) throws IOException {
  25. try {
  26. Field f = exchange.getClass().getDeclaredField("impl");
  27. f.setAccessible(true);
  28. Object obj = f.get(exchange);
  29. f = obj.getClass().getDeclaredField("connection");
  30. f.setAccessible(true);
  31. obj = f.get(obj);
  32. f = obj.getClass().getDeclaredField("chan");
  33. f.setAccessible(true);
  34. SocketChannel chan = (SocketChannel) f.get(obj);
  35. System.out.println("Remote address: " + chan.getRemoteAddress());
  36. } catch (Exception e) {
  37. e.printStackTrace();
  38. }
  39. try {
  40. try (BufferedReader reader = new BufferedReader(
  41. new InputStreamReader(exchange.getRequestBody(), UTF8)))
  42. {
  43. String s;
  44. while ((s = reader.readLine()) != null) {
  45. System.out.println("Input: " + s);
  46. }
  47. }
  48. exchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, 0);
  49. try (OutputStream os = exchange.getResponseBody()) {
  50. for (int j = 0; j < 3; ++j) {
  51. os.write(("Lesson #" + (j + 1)).getBytes(UTF8));
  52. for (int i = 0; i < 10; ++i) {
  53. os.write("I will use Google before asking dumb questions".getBytes(UTF8));
  54. Thread.sleep(100);
  55. }
  56. os.flush();
  57. }
  58. }
  59. } catch (InterruptedException e) {
  60. e.printStackTrace();
  61. }
  62. }
  63. }
  64.  
  65. public class Main {
  66. public static void main(final String[] args) throws Exception {
  67. HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0);
  68. server.createContext("/", new Handler());
  69. server.setExecutor(null);
  70. server.start();
  71. Thread.sleep(1000);
  72. server.stop(0);
  73. }
  74. }
Success #stdin #stdout 0.11s 216832KB
stdin
Standard input is empty
stdout
Standard output is empty