0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Javaによる簡易HTTPサーバの作り方

Posted at

Tomcat等を使わずにJavaだけでHTMLを公開するプログラムを書いてみた。

test@test-ThinkPad-X280:~/test/javatest$ javac MiniContainerSocketHTML.java 
test@test-ThinkPad-X280:~/test/javatest$ java MiniContainerSocketHTML 
Running on http://localhost:8081/

image.png
76cd2d7f6baa8.jpg

MiniContainerSocketHTML.java
import java.io.*;
import java.net.*;

public class MiniContainerSocketHTML {
    public static void main(String[] args) throws Exception {
        ServerSocket server = new ServerSocket(8081);
        System.out.println("Running on http://localhost:8081/");

        while (true) {
            Socket client = server.accept();//クライアント(例: ブラウザ)が localhost:8081に TCP接続してくるまで待つ
            handleClient(client);
            //new Thread(() -> handleClient(client)).start(); //同時に複数のリクエストを処理したい場合の書き方
        }
    }

    private static void handleClient(Socket client) throws IOException{

        InputStream in = client.getInputStream();
        OutputStream out = client.getOutputStream();
        // ブラウザから送られてくるHTTPリクエスト1行目を読む
        char[] buf = new char[1024];
        int idx = 0;
        int c;
        while ((c = in.read()) != -1) {
            if (c == '\r') continue; // HTTPではCRLFなのでCRは無視
            if (c == '\n') break; // LFで1行終わり
    	    buf[idx++] = (char)c;
        }
        String requestLine = new String(buf, 0, idx);
        System.out.println("Request: " + requestLine);

        // 例 "GET /hello HTTP/1.1" → ["GET", "/hello", "HTTP/1.1"]
        // "/hello"だけ取り出す
        String path = "/";
        if (!requestLine.isEmpty()) {
            path = requestLine.split(" ")[1];
        }

        String body;
        if ("/hello".equals(path)) {
            body = "<html><body><h1>Hello!</h1></body></html>";
        } else {
            body = "<html><body><h1>404 Not Found</h1></body></html>";
        }

        String headers = "HTTP/1.1 " + ("/hello".equals(path) ? "200 OK" : "404 Not Found") + "\r\n" +
	             "Content-Length: " + body.getBytes("UTF-8").length + "\r\n" +
	             "Content-Type: text/html; charset=UTF-8\r\n" +
	             "\r\n";

        out.write(headers.getBytes("UTF-8"));
        out.write(body.getBytes("UTF-8"));
        out.flush();//バッファに溜まっているデータを強制的に送信する
        client.close();
        
    }
}
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?