Java Socket Response HTTProtocol

我們可以寫一小串程式,並且於瀏覽器上瀏覽lcoalhost:8080的網址,基本上就會看到Hello World!

public class HttpSocketServer extends Thread{

    private static Logger logger = Logger.getLogger(HttpSocketServer.class);

    private static final int SERVER_PORT = 8080;

    private ServerSocket serverSocket;

    private boolean isRunning = true;

    public HttpSocketServer() {

        logger.info("初始化Server中...");

        try {
            serverSocket = new ServerSocket(SERVER_PORT);
        } catch (Exception e) {
            logger.error("Server初始化失敗...", e);
        }
    }

    public void startServer() {
        logger.info("Server已經啟動...");

        while (isRunning) {
            try {

                Socket clientSocket = serverSocket.accept();

                logger.info("取得連線,InetAddress = " + clientSocket.getInetAddress());

                String response = "<html><head></head><body><h1>Hello World!</h1></body></html>";
                String today = new Date().toString();

                PrintWriter out = new PrintWriter(clientSocket.getOutputStream());
                out.print("HTTP/1.1 200 \r\n"); // 版本 HTTP/1.1 ; 狀態 200
                out.print("Content-Type: text/html; charset=UTF-8\r\n"); //這應該不用解釋惹
                out.print("Content-length: " + response.length() + "\r\n"); //這部分對於HTTP 1.1非常重要,若沒有回傳正確長度,網頁87%會出問題
                out.print("Status: 200\r\n"); 
                out.print("Date: " + today + "\r\n");
                out.print("\r\n"); // 結束協定
                out.print(response); //通常結束協定後面都會接上我們的資料。
                out.flush(); //更新數據

            } catch (Exception e) {
                logger.error("Socket連線有問題...", e);
            }
        }
    }

    @Override
    public void run() {
        startServer();
    }

    public static void main(String args[]) {
        (new HttpSocketServer()).start();
    }

}

結果

這邊我們可以先看看瀏覽器送甚麼Request給我們,這是最基本的Header請求,在Request上面就是我們Response的東西。

results matching ""

    No results matching ""