Javaに基づく最も簡単なWebサーバ


最近Javaのネットワークプログラミングを勉強しています。簡単な例を見ましたが、Webアクセスの機能を実現しました。もちろん、TomcatやWeblogicなどのWebサーバーはもちろん比べることができません。しかし、最も基本的なウェブアクセスのネットワーク原理の実現を示しています。
   
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
public class HTTPThread implements Runnable {
          
    private Socket socket;
    private int count;
    public HTTPThread(){
              
    }
          
    public HTTPThread(Socket socket, int count){
        this.socket = socket;
        this.count = count;
    }
    @Override
    public void run() {
        // TODO Auto-generated method stub
        try {
            OutputStream os = socket.getOutputStream();
            PrintWriter pw = new PrintWriter(os);
            pw.println("<html>");
            pw.println("<head>");
            pw.println("<body>");
            pw.println("This my page! You are welcome!");
            pw.println("</body>");
            pw.println("</head>");
            pw.println("</html>");
                  
            pw.flush();
            pw.close();
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class TCPServer {
    public static void main(String[] args){
        int count = 1;
        try {
            ServerSocket ss = new ServerSocket(8080);
            Socket s = null;
            while((s=ss.accept()) != null){
                System.out.println("The visitor:" + count);
                HTTPThread httpThread = new HTTPThread(s, count);
                Thread thread = new Thread(httpThread);
                thread.start();
                count++;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
   コンパイル運転後、ブラウザでアクセスhttp://localhost:8080/いいです。不思議ですね。