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/
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();
}
}