基於Java的最簡單的Web服務器

   近日學習Java的網絡編程,看到一個及其簡單的例子,但是卻實現了一次Web訪問的功能,當然,於Tomcat和Weblogic等Web服務器自然是沒法比,可是展現了最基本的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/就可以了,是不是很神奇呢!


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章