diff --git a/src/j3/Thttpd.java b/src/j3/Thttpd.java index 8559ca6..356d992 100644 --- a/src/j3/Thttpd.java +++ b/src/j3/Thttpd.java @@ -13,6 +13,7 @@ import java.io.InputStreamReader; import java.net.ServerSocket; import java.net.Socket; +import java.time.LocalDateTime; // Thttpdクラス public class Thttpd { @@ -24,8 +25,8 @@ // その他 if (args.length == 0) // 引数がない場合、以下のファイルを返すことにする - args = new String[] { "src/j3/index.html" }; //相対パスで指定。windowsの場合、user.dir=NWP - // args = new String[] { "j3/index.html" };//Linuxの場合、通常はcd NWP/src しているはず + args = new String[] { "src/j3/index.html" }; // 相対パスで指定。windowsの場合、user.dir=NWP + // args = new String[] { "j3/index.html" };//Linuxの場合、通常はcd NWP/src しているはず System.out.println("このサーバは" + args[0] + "を返します。"); System.out.println(System.getProperty("user.dir")); try { @@ -42,7 +43,6 @@ } } - class RequestHandler implements Runnable { Socket sock; Thread thread; @@ -61,14 +61,15 @@ thread.start(); } - public void run(){ + public void run() { try { process(); } catch (IOException e) { e.printStackTrace(); } thread = null; - } + } + void process() throws IOException { System.out.println("---\nConnection Requst from: " + (sock.getInetAddress())); // 読み書き用オブジェクトの生成 @@ -77,23 +78,37 @@ // read headers StringBuffer request = new StringBuffer(); String line; + String[] get = null; // GETリクエストをスペースで区切った配列 while ((line = in.readLine()) != null) { System.out.println(line); + // 先頭がGETだったら + if (line.toLowerCase().startsWith("get ")) { + get = line.split(" "); // GET / HTTP/1.1 をスペースで区切った配列get を得る + } request.append(line + "\r\n"); if (line.length() < 1) break; } - // Response Headerの出力 String CRLF = "\r\n"; + // Response Headerの出力 String response = "HTTP/1.1 200" + CRLF + "Content-type: text/html; charset=UTF-8" + CRLF + CRLF; + // もし、リクエストがfaviconだったら + if (get[1].endsWith(".ico")) { + response = "HTTP/1.1 200" + CRLF + "Content-type: image/x-icon" + CRLF + CRLF; + } else if (get[1].endsWith(".java")) { + response = "HTTP/1.1 200" + CRLF + "Content-type: text/plain; charset=UTF-8" + CRLF + CRLF; + } + if (!get[1].equals("/")) { // リクエストファイルがあれば、/index.html の部分を書き換える + file = file.replaceAll("/index.html", get[1]); + } // オブジェクトinfileを作り,ファイルを準備します try { infile = new FileInputStream(file); } catch (Exception e) { // ファイル準備の失敗 - System.err.println("ファイルがありません"); - System.exit(1); + System.err.println(file + " ファイルがありません"); + response = "HTTP/1.1 404" + CRLF + CRLF; } dostr.write(response.getBytes()); @@ -108,12 +123,16 @@ cont = false; } } - // おまけ:レスポンスヘッダを表示 - dostr.write(request.toString().getBytes()); + if (file.endsWith("index.html")) { + // おまけ:レスポンスヘッダを表示 + dostr.write(request.toString().getBytes()); + // おまけ:時刻表示 + dostr.write(" \n\n