web服務器原理

web服務器原理

  1、參照博客,複製代碼到idea中。在src包中創建Request.java文件,代碼如圖:html

  

 
 
import java.io.*;
public class Request {
/*
* 接收請求的信息,並返回資源(文件名)
* */
InputStream input;
public Request(InputStream input)
{
this.input=input;
}
public String getUri() throws IOException
{
String content=null,str=null;
StringBuffer request = new StringBuffer();
byte[] buffer = new byte[2048];
int i = 0;

try {
i = input.read(buffer); //讀取內容並存入buffer數組中,並返回讀取的的字節數。
} catch (IOException e) {
e.printStackTrace();
i = -1;
}
//將buffer數組轉換爲字符串
for(int k = 0; k < i; k++) {
request.append((char)buffer[k]);
}
content=request.toString();
/*
*如下方法錯誤!用該返回會使瀏覽器不斷處於請求鏈接狀態
* BufferedReader br=new BufferedReader(new InputStreamReader(input));
while((str=br.readLine())!=null)
{
content=content+str+"\r\n";
}
*/
if(content!=null)
return getFilename(content);
else return null;
}
/*提取文件名*/
public String getFilename(String content)
{
int a,b;
a=content.indexOf(' ');
if(a!=-1)
{
b=content.indexOf('?',a+1);
if(b==-1)b=content.indexOf(' ',a+1);
return content.substring(a+2,b);
}
return null;
}
}
 

  創建Response.java文件java

import java.io.*; import java.io.File; import java.io.IOException; import java.io.OutputStream; public class Response { /** * 響應並處理請求信息 */ public OutputStream output; public String filename; private static final int BUFFER_SIZE = 1024; public Response(OutputStream output,String filename) { this.output=output; this.filename=filename; } public void response() throws IOException { String path=System.getProperty("user.dir");//獲取當前的工做目錄 byte[] buffer = new byte[BUFFER_SIZE]; int ch; FileInputStream fis = null; System.out.println(path+File.separator+filename); if(path!=null&&filename!=null) { System.out.println(path+File.separator+filename); File file=new File(path,filename); String str=""; /*必須添加響應頭,不然沒法以html格式顯示內容*/ if(file.exists()) { // System.out.println(1111); fis = new FileInputStream(file); str = "HTTP/1.1 200 OK \r\n" + "Content-Type: text/html\r\n" + "\r\n" ; output.write(str.getBytes()); ch = fis.read(buffer); while(ch != -1) { System.out.println(ch); output.write(buffer, 0, ch); ch = fis.read(buffer, 0, BUFFER_SIZE); } } else { // 200 OK str = "HTTP/1.1 200 File Not Found \r\n" + "Content-Type: text/html\r\n" + "Content-Length: 100\r\n" + "\r\n" + "<h1>404 File Not Found!</h1>"+ "\r\n" + "2222"; System.out.println(str); File fil=new File(path,"123.html"); fis = new FileInputStream(fil); output.write(str.getBytes()); ch = fis.read(buffer); while(ch != -1) { System.out.println(ch); output.write(buffer, 0, ch); ch = fis.read(buffer, 0, BUFFER_SIZE); } // output.write(str.getBytes());  } } output.close(); } }

  創建服務器java類:WebServer.javaweb

import java.io.*; import java.net.*; public class WebServer { /** * web服務器:實現200和404操做 * 原理: * 服務器監聽一個端口,並讀取瀏覽器的請求信息,從該信息提取出訪問的資源(這裏爲文件名)。並在工做目錄下查找是否有該資源,有則輸出資源內容,不然返回404 * 測試方法: * 一、用String path=System.getProperty("user.dir");獲取當前的工做目錄,並在該目錄下放要測試的文件 * 二、訪問127.0.0.1:8080/test.html */ public static void main(String[] args) { // TODO Auto-generated method stub ServerSocket server = null; Socket s=null; try { server=new ServerSocket(11113,3,InetAddress.getByName("127.0.0.1")); // server=new ServerSocket(8080); }catch(Exception e) { e.printStackTrace(); } while(true) { try{ s=server.accept(); System.out.println(s.toString()); OutputStream output=s.getOutputStream(); InputStream input=s.getInputStream(); //接收請求信息 Request request=new Request(input); String filename=request.getUri(); System.out.println(filename); //處理並響應請求信息 Response response=new Response(output,filename); response.response(); }catch(Exception e) { System.out.println("111"); e.printStackTrace(); } } } }

1、服務器端口占用問題

第一次運行後,在遊覽器端訪問的時候拋出異常以下:數組

通過逐次排查和百度後發現是new ServerSocket()傳入參數時的端口占有問題,拋出的常見異常爲ServerSocket爲空指針異常,由於idea裏爲Tomcat配置的默認端口爲8080,可能在後臺運行着其它Servlet服務,或者對該Web服務器存在着屢次的啓動。瀏覽器

解決方法: 1.修改傳入參數爲其餘的端口。服務器

      2.查看本身的idea或者eclipse是否存在以下圖的服務器的屢次啓動問題,此時頭一個服務器並無關閉,因此存在了端口的佔用。app

2、遊覽器劫持404,攔截自定義的404頁面

 在沒有創建本身工程下的HTML文件時,遊覽器訪問會出現如圖所示的問題,並非本身定義404頁面eclipse

解釋:測試了幾個不一樣的遊覽器對此404問題的解決方法,和修改Response中字符串的響應頭404爲202等即可以正常顯示以下:socket

3、創建html文件的路徑問題

  學習過Servlet的朋友習慣下會把src或者web目錄做爲HTML訪問的根目錄(是由於Tomcat服務器通過處理),因此常常在測試的時候把.html,.jsp等文件創建在這兩個目錄下。可是自定義web服務器中,咱們是經過System.getProperty("user.dir")方法獲取當前的工做目錄,因此.html文件須要創建在與src,web等相同的目錄下才能夠正常訪問。jsp

4、web服務器的運行流程

  Web服務器的工做原理通常能夠分爲以下4個步驟:鏈接過程、請求過程、應答過程、關閉鏈接。

  鏈接過程就是web服務器和其遊覽器之間創建的一種鏈接,查看鏈接過程是否實現,用戶能夠找到和打開socket這個虛擬文件,這個文件的創建意味着鏈接過程已經成功創建。

  請求過程就是web的服務器運用socket這個文件向其服務發出的各類請求。

  應答過程就是運用http協議把在請求過程當中所提出的請求傳輸到web的服務器,進而實施任務處理,而後運用http協議與把處理結果傳輸到web的遊覽器,由遊覽器進行解析和渲染過程。

  關閉鏈接就是完成應答過程後服務器和遊覽器之間斷開的過程。

相關文章
相關標籤/搜索