這個簡單的web伺服器包含三個類 HttpServer Request Response 在應用程式的入口點,也就是靜態main函數中,創建一個HttpServer實例,然後調用其await()方法。顧名思義,await方法會在制定的埠上等待http請求,並對其進行處理,然後發送相應的消息回客戶端 ...
這個簡單的web伺服器包含三個類
- HttpServer
- Request
- Response
在應用程式的入口點,也就是靜態main函數中,創建一個HttpServer實例,然後調用其await()方法。顧名思義,await方法會在制定的埠上等待http請求,並對其進行處理,然後發送相應的消息回客戶端。在接收到命令之前,它會一直保持等待的狀態。
- HttpServer類
package simpleHttpServer;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
public class HttpServer {
public static final String WEB_ROOT = System.getProperty("user.dir") + File.separator
+ "webroot";
private static final String SHUTDOWN_COMMAND = "/SHUTDOWN";
private boolean shudown = false;
public static void main(String[] args){
HttpServer server = new HttpServer();
server.await();
}
public void await(){
ServerSocket serverSocket = null;
int port = 8080;
try{
serverSocket = new ServerSocket(port,1,InetAddress.getByName("127.0.0.1"));
}
catch (IOException e){
e.printStackTrace();
System.exit(1);
}
while(!this.shudown){
Socket socket = null;
InputStream input = null;
OutputStream output = null;
try{
socket = serverSocket.accept();
input = socket.getInputStream();
output = socket.getOutputStream();
Request request = new Request(input);
request.parse();
Response response = new Response(output);
response.setRequest(request);
response.sendStaticResource();
socket.close();
this.shudown = request.getUri().equals(SHUTDOWN_COMMAND);
}
catch (Exception e){
e.printStackTrace();
continue;
}
}
}
}
這個簡單的web伺服器,可以處理指定目錄中的靜態資源請求;用WEB_ROOT表示制定的目錄
public static final String WEB_ROOT = System.getProperty("user.dir") + File.separator + "webroot";
這裡是指當前目錄下的webroot文件夾下麵的資源。
我們通過在游覽器中輸入這樣的內容,進行資源的請求:
http://127.0.0.1:8080/index.html
- Request類
Request類表示一個Http請求,可以傳遞InputStream對象來創建Request對象,調用InputStream對象的read進行Http請求數據的讀取。
package simpleHttpServer;
import java.io.InputStream;
public class Request {
private InputStream input;
private String uri;
public Request(InputStream input){
this.input = input;
}
public void parse(){
StringBuffer request = new StringBuffer(2048);
int i;
byte[] buffer = new byte[2048];
try{
i = input.read(buffer);
}
catch (Exception e){
e.printStackTrace();
i = -1;
}
for(int j=0;j<i;j++){
request.append((char)buffer[j]);
}
System.out.print(request.toString());
this.uri = this.parseUri(request.toString());
}
private String parseUri(String requestString){
int index1,index2;
index1 = requestString.indexOf(' ');
if(index1 != -1){
index2 = requestString.indexOf(' ', index1 + 1);
if(index2 > index1){
return requestString.substring(index1 + 1,index2 );
}
}
return null;
}
public String getUri(){
return this.uri;
}
}
Request類最重要的兩個函數是parse和ParseUri;parse()方法會調用私有方法parseUri來解析HTTP請求的uri,初次之外,並沒有做太多的工作。parseuri會將解析的URI存儲在變數uri中。
我們以 http://127.0.0.1:8080/index.html 請求為例,HTTP請求的請求行為
GET /index.html HTTP/1.1
parse()方法從傳入的Request對象的InputStream對象中讀取整個位元組流,並且將位元組數組存入緩衝區。然後用緩存區的數組初始化StringBuffer對象request。 這樣再解析StringBuffer就可以解析到Uri。
*Response類
Response類表示Http相應。其定義如下
package simpleHttpServer;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
public class Response {
private static final int BUFFER_SIZE = 1024;
private Request request;
private OutputStream output;
public Response(OutputStream output){
this.output = output;
}
public void setRequest(Request request){
this.request = request;
}
public void sendStaticResource()throws IOException{
byte[] bytes = new byte[BUFFER_SIZE];
FileInputStream fis = null;
try{
File file = new File(HttpServer.WEB_ROOT,request.getUri());
if(file.exists()){
fis = new FileInputStream(file);
int ch = fis.read(bytes, 0, BUFFER_SIZE);
while(ch != -1){
output.write(bytes, 0, ch);
ch = fis.read(bytes, 0, BUFFER_SIZE);
}
}
else{
String errorMessage = "HTTP/1.1 404 File Not Found\r\n" +
"Content-Type: text/html\r\n" +
"Content-Length:23\r\n" +
"\r\n" +
"<h1>File Not Found</h1>";
output.write(errorMessage.getBytes());
}
}
catch (Exception e){
e.printStackTrace();
}
finally{
if(fis != null){
fis.close();
}
}
}
}
使用OutputStream和Request來初始化Reponse,Response比較簡單,得到Request的Uri,然後讀取對應的file,如果file存在,則將file中的數據讀取到緩存中,並且發送給游覽器;如果file不存在,那麼就發送
"HTTP/1.1 404 File Not Found\r\n" +
"Content-Type: text/html\r\n" +
"Content-Length:23\r\n" +
"\r\n" +
"<h1>File Not Found</h1>";
錯誤信息給游覽器。
我們在eclipse中將代碼跑起來,在游覽器中輸入
http://127.0.0.1:8080/index.html
http://127.0.0.1:8080/index.php
一個簡單的額web伺服器就跑起來了!