Web服務(wù)器也稱(chēng)為超文本傳輸協(xié)議服務(wù)器,使用http與其客戶端進(jìn)行通信,基于java的web服務(wù)器會(huì)使用兩個(gè)重要的類(lèi),
java.net.Socket類(lèi)和java.net.ServerSocket類(lèi),并基于發(fā)送http消息進(jìn)行通信。
這個(gè)簡(jiǎn)單的Web服務(wù)器會(huì)有以下三個(gè)類(lèi):
*HttpServer
*Request
*Response
應(yīng)用程序的入口在HttpServer類(lèi)中,main()
方法創(chuàng)建一個(gè)HttpServer實(shí)例,然后調(diào)用其await()方法,顧名思義,await()
方法會(huì)在指定端口上等待HTTP請(qǐng)求,對(duì)其進(jìn)行處理,然后發(fā)送響應(yīng)信息回客戶端,在接收到關(guān)閉命令前,它會(huì)保持等待狀態(tài)。
該應(yīng)用程序僅發(fā)送位于指定目錄的靜態(tài)資源的請(qǐng)求,如html文件和圖像,它也可以將傳入到的http請(qǐng)求字節(jié)流顯示到控制臺(tái),但是,它并不發(fā)送任何頭信息到瀏覽器,如日期或者cookies等。
下面為這幾個(gè)類(lèi)的源碼
Request:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
|
package cn.com.server; import java.io.InputStream; public class Request { private InputStream input; private String uri; public Request(InputStream input){ this .input=input; } public void parse(){ //Read a set of characters from the socket 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()); uri=parseUri(request.toString()); } public 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類(lèi)表示一個(gè)HTTP請(qǐng)求,可以傳遞InputStream對(duì)象來(lái)創(chuàng)建Request對(duì)象,可以調(diào)用InputStream對(duì)象中的read()
方法來(lái)讀取HTTP請(qǐng)求的原始數(shù)據(jù)。
上述源碼中的parse()
方法用于解析Http請(qǐng)求的原始數(shù)據(jù),parse()方法會(huì)調(diào)用私有方法parseUrI()
來(lái)解析HTTP請(qǐng)求的URI,除此之外,并沒(méi)有做太多的工作,parseUri()
方法將URI存儲(chǔ)在變量uri中,調(diào)用公共方法getUri()
會(huì)返回請(qǐng)求的uri。
Response:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
|
package cn.com.server; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.OutputStream; /** * HTTP Response = Status-Line * *(( general-header | response-header | entity-header ) CRLF) * CRLF * [message-body] * Status-Line=Http-Version SP Status-Code SP Reason-Phrase CRLF * */ public class Response { private static final int BUFFER_SIZE= 1024 ; Request request; 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 , BUFFER_SIZE); ch=fis.read(bytes, 0 , BUFFER_SIZE); } } else { //file not found 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) { System.out.println(e.toString()); } finally { if (fis!= null ){ fis.close(); } } } } |
Response對(duì)象在HttpServer類(lèi)的await()
方法中通過(guò)傳入套接字中獲取的OutputStream來(lái)創(chuàng)建。
Response類(lèi)有兩個(gè)公共方法:setRequest()
和sendStaticResource()
,setRequest()
方法會(huì)接收一個(gè)Request對(duì)象為參數(shù),sendStaticResource()
方法用于發(fā)送一個(gè)靜態(tài)資源到瀏覽器,如Html文件。
HttpServer:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
|
package cn.com.server; import java.io.File; import java.io.InputStream; import java.io.OutputStream; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; public class HttpServer { /** * WEB_ROOT is the directory where our html and other files reside. * For this package,WEB_ROOT is the "webroot" directory under the * working directory. * the working directory is the location in the file system * from where the java command was invoke. */ public static final String WEB_ROOT=System.getProperty( "user.dir" )+File.separator+ "webroot" ; private static final String SHUTDOWN_COMMAND= "/SHUTDOWN" ; private Boolean shutdown= 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 (Exception e) { e.printStackTrace(); System.exit( 0 ); } while (!shutdown){ Socket socket= null ; InputStream input= null ; OutputStream output= null ; try { socket=serverSocket.accept(); input=socket.getInputStream(); output=socket.getOutputStream(); //create Request object and parse Request request= new Request(input); request.parse(); //create Response object Response response= new Response(output); response.setRequest(request); response.sendStaticResource(); } catch (Exception e) { e.printStackTrace(); continue ; } } } } |
這個(gè)類(lèi)表示一個(gè)Web服務(wù)器,這個(gè)Web服務(wù)器可以處理對(duì)指定目錄的靜態(tài)資源的請(qǐng)求,該目錄包括由公有靜態(tài)變量final WEB_ROOT指明的目錄及其所有子目錄。
現(xiàn)在在webroot中創(chuàng)建一個(gè)html頁(yè)面,命名為index.html,源碼如下:
1
2
3
4
5
6
7
8
9
10
|
<!DOCTYPE html> < html > < head > < meta charset = "UTF-8" > < title >Insert title here</ title > </ head > < body > < h1 >Hello World!</ h1 > </ body > </ html > |
現(xiàn)在啟動(dòng)該WEB服務(wù)器,并請(qǐng)求index.html靜態(tài)頁(yè)面。
所對(duì)應(yīng)的控制臺(tái)的輸出:
如此,一個(gè)簡(jiǎn)單的http服務(wù)器便完成了。
總結(jié)
以上就是本文關(guān)于java實(shí)現(xiàn)一個(gè)簡(jiǎn)單的Web服務(wù)器實(shí)例解析的全部?jī)?nèi)容,希望對(duì)大家有所幫助。感興趣的朋友可以繼續(xù)參閱本站其他相關(guān)專(zhuān)題,如有不足之處,歡迎留言指出。感謝朋友們對(duì)本站的支持!
原文鏈接:http://blog.csdn.net/u012734441/article/details/44801523