概念
其實本質(zhì)是用到了socket。
1,首先客戶端即瀏覽器訪問自己設定的端口為9999的socket。
http://localhost:9999/a.png
2,服務器端就要將瀏覽器請求的數(shù)據(jù)進行解析,找到請求頭中資源在tomcat中的位置的url,然后tomcat在自己本地尋找是否有這樣的位置,如果找到了就按照瀏覽器響應的格式加上協(xié)議頭部發(fā)送請求。
- 服務器端開啟端口為9999的socket等待客戶端來訪問它。
public TomdogMain() {
try {
ServerSocket ss=new ServerSocket(9999);
System.out.println("tomdog 已經(jīng)在9999端口啟動");
while (true) {
Socket client=ss.accept();
System.out.println("有客戶端鏈接起來了");
new TomdogThread(client).start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
- 創(chuàng)建這個類的時候就可以獲取客戶端發(fā)送過來的請求。 并通過io流接收它。
public TomdogThread(Socket socket) {
this.socket=socket;
try {
br=new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
out=new PrintStream(this.socket.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
}
- 解析請求的數(shù)據(jù),找到資源所在的位置,在這里就是找到C:\test\ROOT這個文件夾下面的資源。
這是頭部的信息:GET /a.png HTTP/1.1
private String parse(BufferedReader br) {
String[] data = null;
try {
String header=br.readLine();
data=header.split(" ");
System.out.println("Method:"+data[0]+"url:"+data[1]+"version:"+data[2]);
} catch (IOException e) {
e.printStackTrace();
}
return data[1];
}
- 給客戶端響應請求,按照下面的格式響應請求,并且判斷一下如果有這個資源就返回200,沒有這個資源就返回404.
Paste_Image.png
private void sendResponse(String url) {
File file=new File(PATH,url);
if(file.exists()){
FileInputStream fileInputStream;
try {
fileInputStream = new FileInputStream(file);
byte [] b=new byte[(int) file.length()];
fileInputStream.read(b);
out.println("HTTP/1.1 200 OK");
out.println();//分割響應的頭部和體部
out.write(b);
out.flush();
out.close();
fileInputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}else{
out.println("HTTP/1.1 404 Not Found");
out.println();
out.print("<html><body><center><h1>File Not Found</h1></center></body></html>");
out.flush();
out.close();
}
}