2012-02-20 50 views
1

我正在用java編寫簡單,不復雜的web服務器代碼。它似乎完成了,但我不太確定如何測試它。有人能指出我正確的方向嗎?所有的編碼都完成了,我只需要測試代碼。我試着從終端運行它,然後用指定的端口連接到本地主機,但我只能得到404 NOT FOUND。我重申,我不認爲這是代碼的問題,但我猜測測試驅動器代碼的方法。想法?How-to Test /「Drive」HttpRequest.java(Web Server)?

import java.io.*; 
import java.net.*; 
import java.util.*; 

final class HttpRequest implements Runnable { 
    final static String CRLF = "\r\n"; 
    Socket socket; 

    // Constructor 
    public HttpRequest(Socket socket) throws Exception { 
     this.socket = socket; 
    } 

    // Implement the run() method of the Runnable interface. 
    public void run() { 
     try { 
      processRequest(); 
     } catch (Exception e) { 
      System.out.println(e); 
     } 
    } 

    private static void sendBytes(FileInputStream fis, OutputStream os) 
    throws Exception { 
    // Construct a 1K buffer to hold bytes on their way to the socket. 
    byte[] buffer = new byte[1024]; 
    int bytes = 0; 

    // Copy requested file into the socket's output stream. 
    while((bytes = fis.read(buffer)) != -1) { 
     os.write(buffer, 0, bytes); 
     } 
    } 

    private static String contentType(String fileName) { 
    if(fileName.endsWith(".htm") || fileName.endsWith(".html")) { 
     return "text/html"; 
    } 
    if(fileName.endsWith(".jpeg") || fileName.endsWith(".jpg")) { 
    return "image/jpeg"; 
    } 
    if(fileName.endsWith(".gif")) { 
    return "image/gif"; 
    } 
    return "application/octet-stream"; 
    } 

    private void processRequest() throws Exception { 
     // Get a reference to the socket's input and output streams. 
     InputStream is = socket.getInputStream(); 
     DataOutputStream os = new DataOutputStream(socket.getOutputStream()); 

     // Set up input stream filters. 
     BufferedReader br = new BufferedReader(new InputStreamReader(is)); 

     // Get the request line of the HTTP request message. 
     String requestLine = new String(br.readLine()); 

     // Display the request line. 
     System.out.println(); 
     System.out.println(requestLine); 

     // Get and display the header lines. 
     String headerLine = null; 
     while ((headerLine = br.readLine()).length() != 0) { 
      System.out.println(headerLine); 
     } 

    // Extract the filename from the request line. 
    StringTokenizer tokens = new StringTokenizer(requestLine); 
    tokens.nextToken(); // skip over the method, which should be "GET" 
    String fileName = tokens.nextToken(); 
    // Prepend a "." so that file request is within the current directory. 
    fileName = "." + fileName; 

    // Open the requested file. 
    FileInputStream fis = null; 
    boolean fileExists = true; 
    try { 
    fis = new FileInputStream(fileName); 
    } catch (FileNotFoundException e) { 
    fileExists = false; 
    } 

    // Construct the response message. 
    String statusLine = null; 
    String contentTypeLine = null; 
    String entityBody = null; 
    if (fileExists) { 
    statusLine = "200 OK" + CRLF; 
    contentTypeLine = "Content-type: " + 
     contentType(fileName) + CRLF; 
    } else { 
    statusLine = "404 NOT FOUND" + CRLF; 
    contentTypeLine = "Content Not Found!" + CRLF; 
    entityBody = "<HTML>" + 
     "<HEAD><TITLE>Not Found</TITLE></HEAD>" + 
     "<BODY>Not Found</BODY></HTML>"; 
    } 

    // Send the status line. 
    os.writeBytes(statusLine); 

    // Send the content type line. 
    os.writeBytes(contentTypeLine); 

    // Send a blank line to indicate the end of the header lines. 
    os.writeBytes(CRLF); 

    // Send the entity body. 
    if (fileExists) { 
    sendBytes(fis, os); 
    fis.close(); 
    } else { 
    os.writeBytes("File DNE: Content Not Found!"); 
    } 

     // Close streams and socket. 
     os.close(); 
     br.close(); 
     socket.close(); 
    } 
    public static void main(String[] args) throws Exception { 
     final ServerSocket ss = new ServerSocket(8080); 
     while (true) 
      new HttpRequest(ss.accept()).run(); 
    } 
} 

解決方案:

解決。事實證明,以測試它,你需要做的是:

1)從終端按通常運行程序,

2)地方,你想嘗試檢索文件(可以說 「example.html的」)在單獨的終端到同一文件夾作爲您的.java文件(S),

3),運行命令$ wget的本地主機:PORT/FILE.EXTENSION

(我使用的端口8080這裏,所以$ wget的本地主機:8080/example.html的)

您現在應該看到,在文件夾中當前是從一個HTML的響應文件「200 OK發送wget命令「」404文件不是服務器「,以及如果前者爲真的文件內容。

我過於複雜了,如評論/回覆......但它已完成。 猜測和檢查ftw。

+0

當你試圖編寫自己的HTTP服務器時,有什麼特別的原因,當時還有很多其他合適的,成熟的,穩定的,經過充分測試的解決方案?考慮一下像http://www.and.org/texts/server-http - 你準備好處理這一切嗎?對於Java,考慮類似[Jetty](http://www.eclipse.org/jetty/) - 一種可嵌入到JVM中的Web服務器,並且可以配置爲完成您想要的操作。 – ziesemer 2012-02-20 03:34:40

+0

這只是我正在上課的一個小項目。這不應該是任何複雜的。功能正常。 – user1034868 2012-02-20 03:36:53

+1

我很難想象有人可以編寫程序但無法弄清楚如何測試的情況。 – 2012-02-20 03:40:34

回答

3

已解決。事實證明,以測試它,你需要做的是:

1)從終端按通常運行程序,

2)地方,你想嘗試檢索文件(可以說 「example.html的」)在單獨的終端到同一文件夾作爲您的.java文件(S),

3),運行命令$ wget的本地主機:PORT/FILE.EXTENSION

(我使用的端口8080這裏,所以$ wget的本地主機:8080/example.html的)

您現在應該看到,在文件夾中當前是從,響應文件發送wget命令「200 OK」或「404文件不是服務器」,如果前者爲真,則連同文件的內容。

我過於複雜了,如評論/回覆......但它已完成。 猜測和檢查ftw。

+0

這對我來說非常完美。謝謝。但有一些適合我的問題的變化。 – ConductedClever 2014-08-17 18:00:20