java服務器的簡單實現過程記錄
一、HTTP
http請求
一般一個http請求包括以下三個部分:
1 請求方法,如get,post
2 請求頭
3 實體
一個http請求的實例如下:
GET /index.jsp HTTP/1.1
Host: localhost:8080
User-Agent: Mozilla/5.0 (Windows NT 5.1; rv:15.0) Gecko/20100101 Firefox/15.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3
Accept-Encoding: gzip, deflate
Connection: keep-alive
註意紅色部分的url,這是我們待會要截取出來的。
http響應
與http請求類似,http響應也包括三個部分
1 協議-狀態碼-描述
2 響應頭
3 響應實體段
二 socket類
套接字是網絡連接的斷點。套接字使得應用程序可以從網絡中讀取數據,可以向網絡中寫入數據。不同計算機上的應用程序可以通過套接字發送或接受字節流。java中提供瞭Socket類來實現這個功能,通過getInputStream和getOutputStream可以獲取網絡中的輸入輸出流。
但是,光靠Socket類還是不能夠實現我們構建一個服務器應用程序的功能的,因為服務器必須時刻待命,因此java裡面提供瞭ServerSocket類來處理等待來自客戶端的請求,當ServerSocket接受到瞭來自客戶端的請求之後,它就會創建一個實例來處理與客戶端的通信。
三 服務器應用程序的實現
首先,我們要構建一個封裝請求信息的類requst,一個響應請求的類response,還要有一個主程序httpServer來處理客戶端來的請求。
package com.lwq; import java.io.IOException; import java.io.InputStream; /** * @author Joker * 類說明 * 將瀏覽器發來的請求信息轉化成字符和截取url */ public class Request { //輸入流 private InputStream input; //截取url,如http://localhost:8080/index.html ,截取部分為 /index.html private String uri; public Request(InputStream inputStream){ this.input = inputStream; } public InputStream getInput() { return input; } public void setInput(InputStream input) { this.input = input; } public String getUri() { return uri; } public void setUri(String uri) { this.uri = uri; } //從套接字中讀取字符信息 public void parse(){ StringBuffer request = new StringBuffer(2048); int i = 0; byte[] buffer = new byte[2048]; try { i = input.read(buffer); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); i = -1; } for(int j = 0;j<i;j++){ request.append((char)(buffer[j])); } System.out.println(request.toString()); uri = parseUri(request.toString()); } //截取請求的url private String parseUri(String requestString){ int index1 = 0; int index2 = 0; index1 = requestString.indexOf(' '); if(index1!=-1){ index2 = requestString.indexOf(' ',index1+1); if(index2>index1){ return requestString.substring(index1+1,index2); } } return null; } }
下面是封裝瞭響應請求的類response:
package com.lwq; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.OutputStream; import java.io.PrintWriter; /** * @author Joker * @version 創建時間:Sep 5, 2012 9:59:53 PM * 類說明 根據相應信息返回結果 */ public class Response { private static final int BUFFER_SIZE = 1024; Request request; OutputStream output; public Response(OutputStream output){ this.output = output; } public void sendStaticResource() throws IOException{ byte[] bytes = new byte[BUFFER_SIZE]; FileInputStream fis = null; File file = new File(HttpServer.WEB_ROOT,request.getUri()); if(file.exists()){ try { 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); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); }catch(IOException e){ e.printStackTrace(); }finally{ if(fis !=null){ fis.close(); } } }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" + " File Not Found "; try { output.write(errorMessage.getBytes()); output.flush(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public Request getRequest() { return request; } public void setRequest(Request request) { this.request = request; } public OutputStream getOutput() { return output; } public void setOutput(OutputStream output) { this.output = output; } public static int getBUFFER_SIZE() { return BUFFER_SIZE; } }
接下來是主程序,
package com.lwq; import java.io.File; import java.io.InputStream; import java.io.OutputStream; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; /** * @author Joker * 類說明 */ public class HttpServer { /** * @param args */ //WEB_ROOT是服務器的根目錄 public static final String WEB_ROOT = System.getProperty("user.dir")+File.separator+"webroot"; //關閉的命令 private static final String SHUTDOWN_COMMAND= "/SHUTDOWN"; public static void main(String[] args) { // TODO Auto-generated method stub 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")); while(true) { try { Socket socket = null; InputStream input = null; OutputStream output = null; socket = serverSocket.accept(); input = socket.getInputStream(); output = socket.getOutputStream(); //封裝request請求 Request request = new Request(input); request.parse(); //封裝response對象 Response response = new Response(output); response.setRequest(request); response.sendStaticResource(); socket.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); continue; } } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
運行httpServer,在瀏覽器中打下http://localhost:8080/index.jsp,就能看到服務器響應的結果瞭。
總結
到此這篇關於java服務器的簡單實現的文章就介紹到這瞭,更多相關java服務器實現內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!