Explorar o código

add http server

runningwater %!s(int64=2) %!d(string=hai) anos
achega
254905bb16

+ 29 - 0
.gitignore

@@ -0,0 +1,29 @@
+### IntelliJ IDEA ###
+out/
+!**/src/main/**/out/
+!**/src/test/**/out/
+
+### Eclipse ###
+.apt_generated
+.classpath
+.factorypath
+.project
+.settings
+.springBeans
+.sts4-cache
+bin/
+!**/src/main/**/bin/
+!**/src/test/**/bin/
+
+### NetBeans ###
+/nbproject/private/
+/nbbuild/
+/dist/
+/nbdist/
+/.nb-gradle/
+
+### VS Code ###
+.vscode/
+
+### Mac OS ###
+.DS_Store

+ 8 - 0
.idea/.gitignore

@@ -0,0 +1,8 @@
+# Default ignored files
+/shelf/
+/workspace.xml
+# Editor-based HTTP Client requests
+/httpRequests/
+# Datasource local storage ignored files
+/dataSources/
+/dataSources.local.xml

+ 6 - 0
.idea/google-java-format.xml

@@ -0,0 +1,6 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project version="4">
+  <component name="GoogleJavaFormatSettings">
+    <option name="enabled" value="true" />
+  </component>
+</project>

+ 6 - 0
.idea/misc.xml

@@ -0,0 +1,6 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project version="4">
+  <component name="ProjectRootManager" version="2" languageLevel="JDK_17" project-jdk-name="17" project-jdk-type="JavaSDK">
+    <output url="file://$PROJECT_DIR$/out" />
+  </component>
+</project>

+ 8 - 0
.idea/modules.xml

@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project version="4">
+  <component name="ProjectModuleManager">
+    <modules>
+      <module fileurl="file://$PROJECT_DIR$/HowTomcatWorks.iml" filepath="$PROJECT_DIR$/HowTomcatWorks.iml" />
+    </modules>
+  </component>
+</project>

+ 11 - 0
HowTomcatWorks.iml

@@ -0,0 +1,11 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<module type="JAVA_MODULE" version="4">
+  <component name="NewModuleRootManager" inherit-compiler-output="true">
+    <exclude-output />
+    <content url="file://$MODULE_DIR$">
+      <sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
+    </content>
+    <orderEntry type="inheritedJdk" />
+    <orderEntry type="sourceFolder" forTests="false" />
+  </component>
+</module>

+ 75 - 0
src/pyrmont/HttpServer.java

@@ -0,0 +1,75 @@
+package pyrmont;
+
+import java.net.Socket;
+import java.net.ServerSocket;
+import java.net.InetAddress;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.io.IOException;
+import java.io.File;
+
+public class HttpServer {
+
+  /** WEB_ROOT is the directory where our HTML and other files reside.
+   *  For this package, WEB_ROOT is the "webroot" directory under the working
+   *  directory.
+   *  The working directory is the location in the file system
+   *  from where the java command was invoked.
+   */
+  public static final String WEB_ROOT =
+    System.getProperty("user.dir") + File.separator  + "webroot";
+
+  // shutdown command
+  private static final String SHUTDOWN_COMMAND = "/SHUTDOWN";
+
+  // the shutdown command received
+  private boolean shutdown = false;
+
+  public static void main(String[] args) {
+    HttpServer server = new HttpServer();
+    server.await();
+  }
+
+  public void await() {
+    ServerSocket serverSocket = null;
+    int port = 8080;
+    try {
+      serverSocket =  new ServerSocket(port, 1, InetAddress.getByName("127.0.0.1"));
+    }
+    catch (IOException e) {
+      e.printStackTrace();
+      System.exit(1);
+    }
+
+    // Loop waiting for a request
+    while (!shutdown) {
+      Socket socket = null;
+      InputStream input = null;
+      OutputStream output = null;
+      try {
+        socket = serverSocket.accept();
+        input = socket.getInputStream();
+        output = socket.getOutputStream();
+
+        // create Request object and parse
+        Request request = new Request(input);
+        request.parse();
+
+        // create Response object
+        Response response = new Response(output);
+        response.setRequest(request);
+        response.sendStaticResource();
+
+        // Close the socket
+        socket.close();
+
+        //check if the previous URI is a shutdown command
+        shutdown = request.getUri().equals(SHUTDOWN_COMMAND);
+      }
+      catch (Exception e) {
+        e.printStackTrace();
+        continue;
+      }
+    }
+  }
+}

+ 49 - 0
src/pyrmont/Request.java

@@ -0,0 +1,49 @@
+package pyrmont;
+
+import java.io.InputStream;
+import java.io.IOException;
+
+public class Request {
+
+  private InputStream input;
+  private String uri;
+
+  public Request(InputStream input) {
+    this.input = input;
+  }
+
+  public void parse() {
+    // Read a set of characters from the socket
+    StringBuffer request = new StringBuffer(2048);
+    int i;
+    byte[] buffer = new byte[2048];
+    try {
+      i = input.read(buffer);
+    }
+    catch (IOException e) {
+      e.printStackTrace();
+      i = -1;
+    }
+    for (int j=0; j<i; j++) {
+      request.append((char) buffer[j]);
+    }
+    System.out.print(request);
+    uri = parseUri(request.toString());
+  }
+
+  private String parseUri(String requestString) {
+    int index1, index2;
+    index1 = requestString.indexOf(' ');
+    if (index1 != -1) {
+      index2 = requestString.indexOf(' ', index1 + 1);
+      if (index2 > index1)
+        return requestString.substring(index1 + 1, index2);
+    }
+    return null;
+  }
+
+  public String getUri() {
+    return uri;
+  }
+
+}

+ 66 - 0
src/pyrmont/Response.java

@@ -0,0 +1,66 @@
+package pyrmont;
+
+import java.io.OutputStream;
+import java.io.IOException;
+import java.io.FileInputStream;
+import java.io.File;
+
+/*
+  HTTP Response = Status-Line
+    *(( general-header | response-header | entity-header ) CRLF)
+    CRLF
+    [ message-body ]
+    Status-Line = HTTP-Version SP Status-Code SP Reason-Phrase CRLF
+*/
+
+public class Response {
+
+  private static final int BUFFER_SIZE = 1024;
+  Request request;
+  OutputStream output;
+
+  public Response(OutputStream output) {
+    this.output = output;
+  }
+
+  public void setRequest(Request request) {
+    this.request = request;
+  }
+
+  public void sendStaticResource() throws IOException {
+    byte[] bytes = new byte[BUFFER_SIZE];
+    FileInputStream fis = null;
+    try {
+      File file = new File(HttpServer.WEB_ROOT, request.getUri());
+      String header = "HTTP/1.1 200 OK\r\n" +
+              "Content-Type: text/html\r\n"+
+              "\r\n";
+      output.write(header.getBytes());
+      if (file.exists()) {
+        fis = new FileInputStream(file);
+        int ch = fis.read(bytes, 0, BUFFER_SIZE);
+        while (ch!=-1) {
+          output.write(bytes, 0, ch);
+          ch = fis.read(bytes, 0, BUFFER_SIZE);
+        }
+      }
+      else {
+        // file not found
+        String errorMessage = "HTTP/1.1 404 File Not Found\r\n" +
+          "Content-Type: text/html\r\n" +
+          "Content-Length: 23\r\n" +
+          "\r\n" +
+          "<h1>File Not Found</h1>";
+        output.write(errorMessage.getBytes());
+      }
+    }
+    catch (Exception e) {
+      // thrown if cannot instantiate a File object
+      System.out.println(e);
+    }
+    finally {
+      if (fis!=null)
+        fis.close();
+    }
+  }
+}

BIN=BIN
webroot/ModernServlet.class


+ 51 - 0
webroot/ModernServlet.java

@@ -0,0 +1,51 @@
+import javax.servlet.*;
+import javax.servlet.http.*;
+import java.io.*;
+import java.util.*;
+
+public class ModernServlet extends HttpServlet {
+
+  public void init(ServletConfig config) {
+    System.out.println("ModernServlet -- init");
+  }
+
+  public void doGet(HttpServletRequest request, 
+    HttpServletResponse response) 
+    throws ServletException, IOException {
+    
+    response.setContentType("text/html");
+    PrintWriter out = response.getWriter();
+    out.println("<html>");
+    out.println("<head>");
+    out.println("<title>Modern Servlet</title>");
+    out.println("</head>");
+    out.println("<body>");
+
+    out.println("<h2>Headers</h2");
+    Enumeration headers = request.getHeaderNames();
+    while (headers.hasMoreElements()) {
+      String header = (String) headers.nextElement();
+      out.println("<br>" + header + " : " + request.getHeader(header));
+    }
+
+    out.println("<br><h2>Method</h2");
+    out.println("<br>" + request.getMethod());
+
+    out.println("<br><h2>Parameters</h2");
+    Enumeration parameters = request.getParameterNames();
+    while (parameters.hasMoreElements()) {
+      String parameter = (String) parameters.nextElement();
+      out.println("<br>" + parameter + " : " + request.getParameter(parameter));
+    }
+
+    out.println("<br><h2>Query String</h2");
+    out.println("<br>" + request.getQueryString());
+
+    out.println("<br><h2>Request URI</h2");
+    out.println("<br>" + request.getRequestURI());
+
+    out.println("</body>");
+    out.println("</html>");
+
+  }
+}

BIN=BIN
webroot/PrimitiveServlet.class


+ 30 - 0
webroot/PrimitiveServlet.java

@@ -0,0 +1,30 @@
+import javax.servlet.*;
+import java.io.IOException;
+import java.io.PrintWriter;
+
+public class PrimitiveServlet implements Servlet {
+
+  public void init(ServletConfig config) throws ServletException {
+    System.out.println("init");
+  }
+
+  public void service(ServletRequest request, ServletResponse response)
+    throws ServletException, IOException {
+    System.out.println("from service");
+    PrintWriter out = response.getWriter();
+    out.println("Hello. Roses are red.");
+    out.print("Violets are blue.");
+  }
+
+  public void destroy() {
+    System.out.println("destroy");
+  }
+
+  public String getServletInfo() {
+    return null;
+  }
+  public ServletConfig getServletConfig() {
+    return null;
+  }
+
+}

+ 32 - 0
webroot/SessionServlet.java

@@ -0,0 +1,32 @@
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServlet;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import javax.servlet.http.HttpSession;
+import java.io.IOException;
+import java.io.PrintWriter;
+
+public class SessionServlet extends HttpServlet {
+  public void doGet(HttpServletRequest request, HttpServletResponse response)
+    throws ServletException, IOException {
+    System.out.println("SessionServlet -- service");
+    response.setContentType("text/html");
+    PrintWriter out = response.getWriter();
+    out.println("<html>");
+    out.println("<head><title>SessionServlet</title></head>");
+    out.println("<body>");
+    String value = request.getParameter("value");
+    HttpSession session = request.getSession(true);
+    out.println("<br>the previous value is " + 
+      (String) session.getAttribute("value"));
+    out.println("<br>the current value is " + value);
+    session.setAttribute("value", value);
+    out.println("<br><hr>");
+    out.println("<form>");
+    out.println("New Value: <input name=value>");
+    out.println("<input type=submit>");
+    out.println("</form>");
+    out.println("</body>");
+    out.println("</html>");
+  }
+}

BIN=BIN
webroot/images/logo.gif


+ 10 - 0
webroot/index.html

@@ -0,0 +1,10 @@
+<html>
+<head>
+<title>Welcome to BrainySoftware</title>
+</head>
+<body>
+<img src="./images/logo.gif">
+<br>
+Welcome to BrainySoftware.
+</body>
+</html>