Loading [MathJax]/extensions/tex2jax.js

2014年8月4日月曜日

純粋なJavaで作るHttpServer

WebサーバというとApacheやIISが必要と思うけど純粋なJavaでもHTMLを表示するだけであれば簡単に作ることができる。 com.sun.net.httpserverを使う手もあるけど勉強もかねてHttpServerを書いてみた。 ここではThreadを単純に使っているけどノンブロッキングチャネルを使う方法もあるのでこちらも試したい。
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class HttpServer {
public static void main(String[] args) throws IOException {
int port = 5000;
ServerSocket serverSocket = new ServerSocket(port);
while (true) {
Socket socket = serverSocket.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String line;
while (!(line = in.readLine()).equals("")) {
System.out.println(line);
}
HttpRequestThread httpRequest = new HttpRequestThread(socket);
httpRequest.start();
}
}
}
class HttpRequestThread extends Thread {
Socket socket;
public HttpRequestThread(Socket socket) {
this.socket = socket;
}
public void run() {
PrintStream client = null;
try {
Path indexPath = Paths.get("index.html");
byte[] indexBytes = Files.readAllBytes(indexPath);
client = new PrintStream(socket.getOutputStream());
client.println("HTTP/1.0 200 OK");
client.println("Content_type:text/html");
client.println();
client.write(indexBytes);
} catch (IOException e) {
e.printStackTrace();
} finally {
client.flush();
client.close();
}
}
}
view raw HttpServer.java hosted with ❤ by GitHub

0 件のコメント: