如何测试;“驾驶”;HttpRequest.java(Web服务器)?

如何测试;“驾驶”;HttpRequest.java(Web服务器)?,java,multithreading,webserver,port,Java,Multithreading,Webserver,Port,我正在用java编写简单、简单的web服务器代码。它似乎已经完成了,但我不太确定如何测试它。有人能给我指出正确的方向吗?所有的编码都完成了,我只需要测试代码。我试着从终端运行它,然后用一个指定的端口连接到localhost,但我只得到404个notfounds。我重申,我不认为这是代码的问题,但我猜测测试驱动所述代码的方法。想法 import java.io.*; import java.net.*; import java.util.*; final class HttpRequest im

我正在用java编写简单、简单的web服务器代码。它似乎已经完成了,但我不太确定如何测试它。有人能给我指出正确的方向吗?所有的编码都完成了,我只需要测试代码。我试着从终端运行它,然后用一个指定的端口连接到localhost,但我只得到404个notfounds。我重申,我不认为这是代码的问题,但我猜测测试驱动所述代码的方法。想法

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();
    }
}
import java.io.*;
导入java.net。*;
导入java.util.*;
最后一个类HttpRequest实现Runnable{
最终静态字符串CRLF=“\r\n”;
插座;
//建造师
公共HttpRequest(套接字)引发异常{
this.socket=socket;
}
//实现Runnable接口的run()方法。
公开募捐{
试一试{
processRequest();
}捕获(例外e){
系统输出打印ln(e);
}
}
私有静态void sendBytes(FileInputStream fis、OutputStream os)
抛出异常{
//构造一个1K缓冲区,在字节到达套接字的过程中保存字节。
字节[]缓冲区=新字节[1024];
int字节=0;
//将请求的文件复制到套接字的输出流中。
而((字节=fis.read(缓冲区))!=-1){
写操作(缓冲区,0,字节);
}
}
私有静态字符串contentType(字符串文件名){
if(fileName.endsWith(“.htm”)| | fileName.endsWith(“.html”)){
返回“text/html”;
}
if(fileName.endsWith(“.jpeg”)| | fileName.endsWith(“.jpg”)){
返回“图像/jpeg”;
}
if(fileName.endsWith(“.gif”)){
返回“image/gif”;
}
返回“应用程序/八位字节流”;
}
私有void processRequest()引发异常{
//获取对套接字的输入和输出流的引用。
InputStream=socket.getInputStream();
DataOutputStream os=新的DataOutputStream(socket.getOutputStream());
//设置输入流过滤器。
BufferedReader br=新的BufferedReader(新的InputStreamReader(is));
//获取HTTP请求消息的请求行。
String requestLine=新字符串(br.readLine());
//显示请求行。
System.out.println();
System.out.println(请求行);
//获取并显示标题行。
字符串标题行=null;
while((headerLine=br.readLine()).length()!=0){
系统输出打印LN(车头线);
}
//从请求行提取文件名。
StringTokenizer令牌=新的StringTokenizer(requestLine);
tokens.nextToken();//跳过该方法,该方法应为“GET”
字符串文件名=tokens.nextToken();
//在“.”前面加上前缀,使文件请求位于当前目录中。
fileName=“.”+文件名;
//打开请求的文件。
FileInputStream fis=null;
布尔fileExists=true;
试一试{
fis=新文件输入流(文件名);
}catch(filenotfounde异常){
fileExists=false;
}
//构造响应消息。
字符串statusLine=null;
字符串contentTypeLine=null;
字符串entityBody=null;
如果(文件存在){
statusLine=“200正常”+CRLF;
contentTypeLine=“内容类型:”+
contentType(文件名)+CRLF;
}否则{
statusLine=“404未找到”+CRLF;
contentTypeLine=“找不到内容!”+CRLF;
entityBody=”“+
“找不到”+
“未找到”;
}
//发送状态行。
操作系统写入字节(状态行);
//发送内容类型行。
写字节(contentTypeLine);
//发送一个空行以指示标题行的结尾。
操作系统写入字节(CRLF);
//发送实体体。
如果(文件存在){
sendBytes(fis、os);
fis.close();
}否则{
os.writeBytes(“文件DNE:未找到内容!”);
}
//关闭流和套接字。
os.close();
br.close();
socket.close();
}
公共静态void main(字符串[]args)引发异常{
最终服务器插座ss=新服务器插座(8080);
while(true)
新的HttpRequest(ss.accept()).run();
}
}
解决方案:


解决了。事实证明,要测试它,您需要做的只是:

1)按照常规从终端运行程序

2)将要尝试检索的文件(比如“example.html”)与.java文件放在同一文件夹中

3)在单独的终端中,运行命令$wget localhost:PORT/FILE.EXTENSION

(我在这里使用了端口8080,所以$wget localhost:8080/example.html)

现在,您应该在当前发送wget命令的文件夹中看到一个html响应文件“200ok”或“404filenotserver”,以及文件的内容(如果前者为true)

我把这件事复杂化了,评论/回复也是如此。。。但是已经完成了。
猜测和检查ftw。

已解决。事实证明,要测试它,您需要做的只是:

1)按照常规从终端运行程序

2)将要尝试检索的文件(比如“example.html”)与.java文件放在同一文件夹中

3)在单独的终端中,运行命令$wget localhost:PORT/FILE.EXTENSION

(我在这里使用了端口8080,所以$wget localhost:8080/example.html)

现在,您应该在当前发送wget命令的文件夹中看到一个响应文件“200ok”或“404filenotserver”,以及文件的内容(如果前者为true)

我把这件事复杂化了,评论/回复也是如此。。。但是已经完成了。
猜测和检查ftw。

当许多其他合适、成熟、稳定且经过良好测试的解决方案已经存在时,您尝试编写自己的HTTP服务器有什么特殊原因吗?骗局