소켓 손 글씨 HTTP 서버

5748 단어 자바socket
public class JHttp {

  private static final Logger logger = Logger.getLogger(JHttp.class.getCanonicalName());

  private static final int NUM_THREADS = 50;

  private static final String INDEX_FILE = "index.html";

  private final File rootDirectory;
  private final int port;

  public JHttp(File rootDirectory, int port) {
    this.rootDirectory = rootDirectory;
    this.port = port;
  }

  public void start() throws IOException {
    ExecutorService pool = Executors.newFixedThreadPool(NUM_THREADS);

    try (ServerSocket server = new ServerSocket(port)) {
      logger.info("Accepting connections on port " + server.getLocalPort());
      logger.info("Document Root: " + rootDirectory);

      while (true) {
        try {
          Socket request = server.accept();
          RequestProcessor r = new RequestProcessor(rootDirectory, INDEX_FILE, request);
          pool.submit(r);
        } catch (IOException e) {
          logger.log(Level.WARNING, "Error accepting connection", e);
        }
      }
    }
  }

  public static void main(String[] args) {
    try {
      URL url = JHttp.class.getClassLoader().getResource("static");
      JHttp jHttp = new JHttp(new File(url.getPath()), 8888);
      jHttp.start();
    } catch (IOException e) {
      logger.log(Level.SEVERE, "server could not start", e);
    }
  }

  private class RequestProcessor implements Runnable {

    private File rootDirectory;
    private String indexFileName = "index.html";
    private Socket connection;


    public RequestProcessor(File rootDirectory, String indexFileName, Socket connection) {
      this.rootDirectory = rootDirectory;
      this.indexFileName = indexFileName;
      this.connection = connection;
    }

    @Override
    public void run() {
      //       

      String root = rootDirectory.getPath();
      try {
        OutputStream raw = new BufferedOutputStream(connection.getOutputStream());
        Writer out = new OutputStreamWriter(raw);
        Reader in = new InputStreamReader(new BufferedInputStream(connection.getInputStream()));

        //          GET /xxx HTTP/1.1
        StringBuilder requestLine = new StringBuilder();
        while (true) {
          int c = in.read();
          if (c == '\r' || c == '
') { break; } requestLine.append((char) c); } String get = requestLine.toString(); logger.info(connection.getRemoteSocketAddress() + " " + get); String[] tokens = get.split("\\s+"); String method = tokens[0]; String version = ""; if ("GET".equals(method)) { String fileName = tokens[1]; if (fileName.endsWith("/")) { fileName += indexFileName;// } // MIME String contentType = URLConnection.getFileNameMap().getContentTypeFor(fileName); if (tokens.length > 2) { version = tokens[2]; } File theFile = new File(rootDirectory, fileName.substring(1, fileName.length())); if (theFile.canRead() && theFile.getCanonicalPath().startsWith(root)) { // , byte[] theData = Files.readAllBytes(theFile.toPath()); if (version.startsWith("HTTP/")) { // MIME sendHeader(out, "HTTP/1.1 200 OK", contentType, theData.length); } // , , writer raw.write(theData); raw.flush(); } else { // String body = new StringBuilder("\r
") .append("File not Find\r
") .append("") .append("

HTTP Error 404 : File Not Found

\r
") .append("\r
") .toString(); sendHeader(out, "HTTP/1.1 404 FileNotFound", "text/html; charset=utf-8", body.length()); out.write(body); out.flush(); } } else { // // String body = new StringBuilder("\r
") .append("File not Find\r
") .append("") .append("

HTTP Error 501 : Not Support

\r
") .append("\r
") .toString(); sendHeader(out, "HTTP/1.1 501 Not Support", "text/html; charset=utf-8", body.length()); out.write(body); out.flush(); } out.close(); in.close(); } catch (IOException e) { logger.log(Level.WARNING, "Error talking to " + connection.getRemoteSocketAddress(), e); } finally { try { connection.close(); } catch (IOException e) { e.printStackTrace(); } } } private void sendHeader(Writer out, String responseCode, String contentType, int length) throws IOException { out.write(responseCode + System.lineSeparator()); out.write("Date: " + new Date() + System.lineSeparator()); out.write("Server: JHTTP 1.0" + System.lineSeparator()); out.write("Content-length: " + length + System.lineSeparator()); out.write("Content-type: " + contentType + System.lineSeparator() + System.lineSeparator()); // out.flush(); } } }

추가 가능 한 추가 기능: 1. 서버 관리 페이지 2. Java Servlet API 지원 3. POST, PUT 4 와 같은 다른 요청 방법 을 지원 합 니 다. 다 중 문서 루트 디 렉 터 리 지원

좋은 웹페이지 즐겨찾기