HttpServer
- package com.whatsmars.tomcat.servlet;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.OutputStream;
- import java.net.InetAddress;
- import java.net.ServerSocket;
- import java.net.Socket;
- /**
- * Created by shenhongxi on 16/3/21.
- */
- public class HttpServer {
- private static final String SHUTDOWN_COMMAND = "/SHUTDOWN";
- private boolean shutdown = false;
- public static void main(String[] args) {
- HttpServer server = new HttpServer();
- server.await();
- }
- private void await() {
- ServerSocket serverSocket = null;
- int port = 8080;
- try {
- serverSocket = new ServerSocket(port, 1, InetAddress.getByName("127.0.0.1"));
- System.out.println("Server started!");
- } catch (IOException e) {
- e.printStackTrace();
- System.exit(1);
- }
- while (!shutdown) {
- Socket socket = null;
- InputStream input = null;
- OutputStream output = null;
- try {
- socket = serverSocket.accept();
- input = socket.getInputStream();
- output = socket.getOutputStream();
- Request request = new Request(input);
- request.parse();
- Response response = new Response(output);
- response.setRequest(request);
- // check if this is a request for a servlet or a static resource
- if (request.getUri().startsWith("/servlet/")) {
- ServletProcessor processor = new ServletProcessor();
- processor.process(request, response);
- } else {
- StaticResourceProcessor processor = new StaticResourceProcessor();
- processor.process(request, response);
- }
- socket.close();
- shutdown = request.getUri().equals(SHUTDOWN_COMMAND);
- } catch (Exception e) {
- e.printStackTrace();
- continue;
- }
- }
- }
- }
Request
- package com.whatsmars.tomcat.servlet;
- import javax.servlet.*;
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.UnsupportedEncodingException;
- import java.util.Enumeration;
- import java.util.Locale;
- import java.util.Map;
- /**
- * Created by shenhongxi on 16/3/21.
- */
- public class Request implements ServletRequest {
- private InputStream input;
- private String uri; // 性能考虑,用byte[]
- public Request(InputStream input) {
- this.input = input;
- }
- public void parse() {
- 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.println(request.toString());
- uri = parseUri(request.toString());
- }
- private String parseUri(String requestStr) {
- // GET /index.html HTTP/1.1
- // Accept: text/plain; text/html
- // ...
- int index1 = requestStr.indexOf(' ');
- int index2;
- if (index1 != -1) {
- index2 = requestStr.indexOf(' ', index1 + 1);
- if (index2 > index1) {
- return requestStr.substring(index1 + 1, index2);
- }
- }
- return null;
- }
- public String getUri() {
- return uri;
- }
- public Object getAttribute(String name) {
- return null;
- }
- public Enumeration<String> getAttributeNames() {
- return null;
- }
- public String getCharacterEncoding() {
- return null;
- }
- public void setCharacterEncoding(String env) throws UnsupportedEncodingException {
- }
- public int getContentLength() {
- return 0;
- }
- }
Response
- package com.whatsmars.tomcat.servlet;
- import javax.servlet.ServletOutputStream;
- import javax.servlet.ServletResponse;
- import java.io.*;
- import java.util.Locale;
- /**
- * Created by shenhongxi on 16/3/21.
- */
- public class Response implements ServletResponse {
- private static final int BUFFER_SIZE = 1024;
- Request request;
- OutputStream output;
- PrintWriter writer;
- public void sendStaticResource() throws IOException {
- byte[] bytes = new byte[BUFFER_SIZE];
- FileInputStream fis = null;
- try {
- File file = new File(Constants.WEB_ROOT, request.getUri());
- 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 {
- String errorMsg = "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(errorMsg.getBytes());
- }
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- if (fis != null) {
- fis.close();
- }
- }
- }
- public Response(OutputStream output) {
- this.output = output;
- }
- public void setRequest(Request request) {
- this.request = request;
- }
- public String getCharacterEncoding() {
- return null;
- }
- public String getContentType() {
- return null;
- }
- public ServletOutputStream getOutputStream() throws IOException {
- return null;
- }
- public PrintWriter getWriter() throws IOException {
- // autoflush is true, println() will flush, but print() will not
- writer = new PrintWriter(output, true);
- return writer;
- }
- }
RequestFacade
- package com.whatsmars.tomcat.servlet;
- import javax.servlet.*;
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.UnsupportedEncodingException;
- import java.util.Enumeration;
- import java.util.Locale;
- import java.util.Map;
- /**
- * Created by shenhongxi on 2016/4/12.
- */
- public class RequestFacade implements ServletRequest {
- private ServletRequest request;
- public RequestFacade(Request request) {
- this.request = request;
- }
- public Object getAttribute(String name) {
- return request.getAttribute(name);
- }
- public Enumeration<String> getAttributeNames() {
- return request.getAttributeNames();
- }
- }
ResponseFacade
- package com.whatsmars.tomcat.servlet;
- import javax.servlet.ServletOutputStream;
- import javax.servlet.ServletResponse;
- import java.io.IOException;
- import java.io.PrintWriter;
- import java.util.Locale;
- /**
- * Created by shenhongxi on 2016/4/12.
- */
- public class ResponseFacade implements ServletResponse {
- private ServletResponse response;
- public ResponseFacade(Response response) {
- this.response = response;
- }
- public String getCharacterEncoding() {
- return response.getCharacterEncoding();
- }
- public String getContentType() {
- return null;
- }
- public ServletOutputStream getOutputStream() throws IOException {
- return null;
- }
- public PrintWriter getWriter() throws IOException {
- return response.getWriter();
- }
- }
ServletProcessor
- package com.whatsmars.tomcat.servlet;
- import javax.servlet.Servlet;
- import javax.servlet.ServletRequest;
- import javax.servlet.ServletResponse;
- import java.io.File;
- import java.io.IOException;
- import java.net.URL;
- import java.net.URLClassLoader;
- import java.net.URLStreamHandler;
- /**
- * Created by shenhongxi on 2016/4/12.
- */
- public class ServletProcessor {
- public void process(Request request, Response response) {
- String uri = request.getUri();
- String servletName = uri.substring(uri.lastIndexOf("/") + 1);
- URLClassLoader loader = null;
- try {
- URL[] urls = new URL[1];
- URLStreamHandler streamHandler = null;
- File classPath = new File(Constants.WEB_ROOT);
- String repository = (new URL("file", null, classPath.getCanonicalPath()
- + File.separator)).toString();
- urls[0] = new URL(null, repository, streamHandler);
- loader = new URLClassLoader(urls);
- } catch (IOException E) {
- E.printStackTrace();
- }
- Class myClass = null;
- try {
- myClass = loader.loadClass(servletName);
- } catch (ClassNotFoundException e) {
- e.printStackTrace();
- }
- Servlet servlet = null;
- try {
- servlet = (Servlet) myClass.newInstance();
- RequestFacade requestFacade = new RequestFacade(request);
- ResponseFacade responseFacade = new ResponseFacade(response);
- // 为了安全考虑,除了实现ServletRequest/ServletResponse的方法,
- // Request/Response中的其他公共方法需对servlet隐藏,所以用外观类
- servlet.service((ServletRequest) requestFacade, (ServletResponse) responseFacade);
- } catch (Exception e) {
- e.printStackTrace();
- } catch (Throwable e) {
- e.printStackTrace();
- }
- }
- }
StaticResourceProcessor
- package com.whatsmars.tomcat.servlet;
- import java.io.IOException;
- /**
- * Created by shenhongxi on 2016/4/12.
- */
- public class StaticResourceProcessor {
- public void process(Request request, Response response) {
- try {
- response.sendStaticResource();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
PrimitiveServlet
- package com.whatsmars.tomcat.servlet;
- import javax.servlet.*;
- import java.io.IOException;
- import java.io.PrintWriter;
- /**
- * Created by shenhongxi on 2016/4/12.
- */
- public class PrimitiveServlet implements Servlet {
- public void init(ServletConfig config) throws ServletException {
- System.out.println("init");
- }
- public ServletConfig getServletConfig() {
- return null;
- }
- public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
- System.out.println("from service");
- PrintWriter out = res.getWriter();
- out.println("Hello. Roses are red.");
- out.print("Violets are blue");
- }
- public String getServletInfo() {
- return null;
- }
- public void destroy() {
- System.out.println("destroy");
- }
- }
Constants
- package com.whatsmars.tomcat.servlet;
- import java.io.File;
- /**
- * Created by shenhongxi on 2016/4/12.
- */
- public class Constants {
- public static final String WEB_ROOT = System.getProperty("user.dir") + File.separator + "whatsmars-tomcat/src/main/webapp"; // 资源文件,class文件等
- }
原文链接:[http://wely.iteye.com/blog/2290575]
时间: 2024-12-11 02:48:35