java模擬http服務器

最近用java簡單實現了http服務器。主要是使用socket在端口監聽瀏覽器的http請求,根據請求信息在服務器端進行路由(讀取html頁面),然後封裝成http格式的響應返回到瀏覽器。代碼如下:

wKioL1UirnThPiFBAAC3C1VM7qQ186.jpg

項目大概這樣。

HttpServer:

package server;


import java.io.*;

import java.net.*;


import router.SocketHandler;


/**

 * http服務器啓動類

 * @author Administrator

 *

 */

public class HttpServer {

    static ServerSocket server = null ;

    static Socket socket ;

    static int PORT = 8888 ;

    static String IP = "127.0.0.1";

    

    public static void waiting(){

try {

   server = new ServerSocket(PORT , 1,  InetAddress.getByName(IP));

   System.out.println("server waiting on " + PORT + " .....");

   while(true){

socket = server.accept();

SocketHandler.handle(socket);

   }

}catch (IOException e) {

   e.printStackTrace();

}

    }


    public static void main(String[] args) {

waiting();

    }

}



socketHandler類:處理鏈接的socket。

package router;


import java.io.*;

import java.net.*;


/**

 * 解析socket

 * @author Administrator

 *

 */

public class SocketHandler {

    

    static Socket socket ;

    static BufferedReader reader = null;

    static PrintWriter out = null ;

    static String requestUri = null ;

    

    public static void handle(Socket socket){

SocketHandler.socket = socket ;

resoveRequest();

sendResponse();

close();

    }

    

    static void close(){

if( out != null)

   out.close();

try {

   if( reader != null)

reader.close();

   if( socket != null)

socket.close();

} catch (IOException e) {

   e.printStackTrace();

}

    }

    

    /**

     * 解析request

     */

    public static void resoveRequest(){

try {

   reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));

   String item = reader.readLine() ;

   

   if( item != null ){

requestUri = item.split(" ")[1];

   }

   

} catch (IOException e) {

  e.printStackTrace();

}

    }

    

    /**

     * 返回response數據

     * @param out

     */

    public static void sendResponse(){

String html = Router.getPageContent(requestUri);

try {

   StringBuffer sb = new StringBuffer();

   out = new PrintWriter(socket.getOutputStream());

   /**

    * response header

    *///

            //封裝http響應

   sb.append("HTTP/1.1 200\r\n");

   sb.append("Server: EvergreenServer\r\n");

   sb.append("Date: Mon, 3 April 2015 13:13:33 GMT\r\n");

   sb.append("Content-type:text/html;\r\n");

   sb.append("Content-Length: "  + html.length() + "\r\n");

   sb.append("\r\n");

   /**

    * content

    */

   sb.append(html);

   out.println(sb.toString());

   out.flush();

   out.close();

} catch (IOException e) {

   e.printStackTrace();

}

    }


}


Router類:(主要實現對請求url的解析。將html內容返回給響應頭。)

package router;


import java.io.*;


/**

 * 路由類

 * @author Administrator

 *

 */

public class Router {

    

    public static String getPageContent(String uri){

File file = new File("web-root" + (uri.lastIndexOf("?") != -1 ? (uri.substring(0, uri.lastIndexOf("?"))) : uri ));

StringBuffer sb = new StringBuffer();

if( file.exists() == false){

   sb.append("<center>404  <h4 style='color:red;'>Page Not Found</h4></center>");

}else{

   BufferedReader bur = null ;

   try {

bur = new BufferedReader(new InputStreamReader(new FileInputStream(file)));

String str = null;

while( (str = bur.readLine()) != null)

   sb.append(str);

   } catch (Exception e) {

   }finally{

if( bur != null)

   try {

bur.close();

   } catch (IOException e) {

   }

   }

}

return  sb.toString() ;

    }


    public static void main(String[] args) {

    }

}

訪問http://localhost:8888/blog/index.html


wKioL1UisAfiDrTIAAETVzfdFIQ339.jpg

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