JAVA實現簡單的HTTP伺服器

來源:互聯網
上載者:User

        用JAVA實現簡單的HTTP伺服器

        實現不難,但也要全面掌握JAVA基礎編程,還需要瞭解HTTP協議,和HTTP伺服器/用戶端的基本工作原理。

        HTTP是一個基於請求/響應模式的、無狀態的協議。用戶端(瀏覽器) 與伺服器端(Web伺服器應用程式)建立串連後,向伺服器發出

一個請求,伺服器對這個請求進行處理,然後返回一個響應資訊,之後雙方的串連被關閉。

        這裡,我們要實現的也就是我們得到“瀏覽器”的請求後,響應"GET"命令的過程。我們先來看看HTTP協議中"GET”命令的格式:
                                GET Request-URI HTTP/1.1   //注意命令列中的空格不能少
        當我們通過瀏覽器的地址欄中直接輸入網址的方式去訪問網頁的時候,瀏覽器採用的就是GET方法向伺服器端請求擷取資源。

        下面就是代碼:

HttpServer類,也就是啟動伺服器的main()方法所在類:

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Properties;

public class HttpServer {

         public static void main(String[] args) {
 
                 try {
                //為了方便程式的通用性,我們定義Properties屬性檔案來配置Web伺服器的跟目錄
                                Properties pro = new Properties();
                                File f = new File("d:\\Properties.txt");    //屬性設定檔放D盤跟目錄
                                InputStream ins = new FileInputStream(f);
                                ServerSocket ss = new ServerSocket(80); //對連接埠80監聽
                                pro.load(ins);     //讀入屬性檔案
   
                                String ph = pro.getProperty("path");   //得到path屬性值
                                System.out.println(ph);
               //迴圈監聽   當得到一個用戶端Socket後 建立並啟動會話線程
                                while(true)
                                      {
                                              Socket sk = ss.accept();
                                              Session se = new Session(sk,ph);
                                              Thread thread = new Thread(se);
                                              thread.start();
                                      }
                       } catch (IOException e) {
  
                                    e.printStackTrace();
                                   }
            }
}

 

Session類,繼承Runnable介面,方便實現伺服器端支援多使用者(多線程),run()方法內實現對GET命令的處理和響應:

import java.io.*;
import java.net.Socket;
import java.util.*;

public class Session implements Runnable {
          private Socket sk;
          private String PATH;
          public static final int MAX_LENGHT = 1024;
   //構造器, 傳遞進來Socket 和web檔案的跟目錄
         public Session(Socket sk, String path) {
                              this.sk = sk;
                              this.PATH = path;
                       }

          public void run() {

                try {
                        BufferedReader br =
                                new BufferedReader(new InputStreamReader(sk.getInputStream()));
                        OutputStream out = sk.getOutputStream();
                      //br 封裝了伺服器端的輸入資料流 用來讀入用戶端發來的請求行s
                        String s = br.readLine();
                        while (s != null) {
                                   System.out.println("用戶端指令:" + s);
                                    if (s.length() < 3)  break;
                                   //取"GET"命令
                                    String cmd = s.substring(0, 3);
                                    if (cmd.equalsIgnoreCase("GET")) {
                                             //取要獲得的檔案名稱
                                            String filename = s.substring(5, s.lastIndexOf(" "));
                                             //filePath為檔案絕對路徑
                                            String filePath = PATH + filename;
                                            System.out.println(filePath);
                                            //讀入檔案到buf數組
                                            File file = new File(filePath);
                                                       if (!file.exists()) {
                                                       filename = "index.html";
                                                       file = new File(PATH + filename);
                                                          }
                                            InputStream in = new FileInputStream(file);
                                            byte[] buf = new byte[MAX_LENGHT];
                                            //寫入檔案到用戶端
                                            int n = 0;
                                            while ((n = in.read(buf)) != -1) {
                                                     out.write(buf, 0, n);
                                                     out.flush();

                                           }
                                 in.close();

                                 }
                           s = br.readLine();

                       }
                      out.close();
                      sk.close();

  } catch (IOException e) {
   e.printStackTrace();
  }

 }

}

提供源碼的下載  如果要測試的話記得一定要在 D盤跟目錄下建立名為:“Properties.txt”的屬性設定檔,並在裡面編寫健值對:path=你的本地web網站跟目錄  。然後編譯-->運行,開啟IE瀏覽器 在地址欄輸入:http://localhost:80/index.html  (連接埠可以任意配置,但要和ServerSocket監聽的連接埠一致)。

 將下載下來的.txt 尾碼名改為.rar 在解壓  (沒辦法,不支援RAR)

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.