计算机网络 实验八 实现一个简单的web服务器(文末附源码)

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
源代码:

  1. HttpServer.java
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 + "src";

    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 = 3654;
        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;
            }
        }
    }
}
  1. Request.java
import java.io.InputStream;
import java.util.HashMap;

public class Request
{
    private InputStream input;

    private String uri, method;
    private String[] args;
    private HashMap<String, String> arg_set = new HashMap<>();

    public Request(InputStream input)
    {
        this.input = input;
    }

    public String get_method()
    {
        return method;
    }

    public HashMap<String, String> get_arg()
    {
        return arg_set;
    }

    public void parse()
    {
        //Read a set of characters from the socket
        StringBuffer request = new StringBuffer(8192);
        int i;
        byte[] buffer = new byte[8192];
        try
        {
            i = input.read(buffer);
        }
        catch (Exception e)
        {
            e.printStackTrace();
            i = -1;
        }
        for (int j = 0; j < i; j++)
        {
            request.append((char) buffer[j]);
        }
        parseUri(request.toString());
    }

    public void parseUri(String requestString)
    {
        int index1, index2;
        method = requestString.substring(0, requestString.indexOf(" "));

        if (method.equals("GET"))
        {
            index1 = requestString.indexOf(" ");
            if (index1 != -1)
            {
                index2 = requestString.indexOf(" ", index1 + 1);
                if (index2 > index1)
                {
                    uri = requestString.substring(index1 + 1, index2);
                }
            }
        }
        else
        {
            index1 = requestString.indexOf(" ");
            if (index1 != -1)
            {
                index2 = requestString.indexOf(" ", index1 + 1);
                if (index2 > index1)
                {
                    uri =  requestString.substring(index1 + 1, index2);
                }
            }

            String[] temp = requestString.split("\n");
            args = temp[temp.length - 1].split("&");

            for (int i = 0; i < args.length; i++)
            {
                String[] entry = args[i].split("=");
                arg_set.put(entry[0], entry[1]);
            }
        }
    }

    public String getUri()
    {
        return this.uri;
    }
}
  1. Response.java
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;

public class Response
{
    private static final int BUFFER_SIZE = 8192;
    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
        {
            String method = request.get_method();
            if (method.equals("GET"))
            {
                File file = new File(HttpServer.WEB_ROOT, request.getUri());
                System.out.println(request.getUri());
                if (file.exists())
                {
                    FileInputStream temp_file = new FileInputStream(file);
                    byte[] byte_stream = temp_file.readAllBytes();
                    if (request.getUri().contains("html"))
                    {
                        String code = new String(byte_stream);
                        String result = "HTTP/1.1 200 OK\r\n" +
                                "Content-Type:text/html\r\n" +
                                "Content-Length:" + byte_stream.length + "\r\n" +
                                "\r\n" + code;
                        output.write(result.getBytes());
                    }
                    else if (request.getUri().contains("jpg"))
                    {
                        String header = "HTTP/1.1 200 OK\r\n" +
                                "Content-Type:image/jpg\r\n" +
                                "Content-Length:" + byte_stream.length + "\r\n" +
                                "\r\n";
                        output.write(header.getBytes(StandardCharsets.UTF_8));
                        output.write(byte_stream);
                    }
                    else
                    {
                        String header = "HTTP/1.1 200 OK\r\n" +
                                "Content-Type:text/plain\r\n" +
                                "Content-Length:" + byte_stream.length + "\r\n" +
                                "\r\n";
                        output.write(header.getBytes(StandardCharsets.UTF_8));
                        output.write(byte_stream);
                    }
                }
                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());
                }
            }
            else
            {
                if (request.getUri().contains("login"))
                {
                    HashMap<String, String> information = request.get_arg();
                    String header = "HTTP/1.1 200 OK\r\n" +
                            "Content-Type:text/html\r\n" +
                            "Content-Length:" + BUFFER_SIZE + "\r\n" +
                            "\r\n";

                    if (information.get("login").equals("3180103654") && information.get("pass").equals("3654"))
                    {
                        header += "<!DOCTYPE html>\n" +
                                "<html>\n" +
                                "<head>\n" +
                                "  <title>Bootstrap 实例</title>\n" +
                                "  <meta charset=\"utf-8\">\n" +
                                "  <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n" +
                                "  <link rel=\"stylesheet\" href=\"https://cdn.staticfile.org/twitter-bootstrap/4.3.1/css/bootstrap.min.css\">\n" +
                                "  <script src=\"https://cdn.staticfile.org/jquery/3.2.1/jquery.min.js\"></script>\n" +
                                "  <script src=\"https://cdn.staticfile.org/popper.js/1.15.0/umd/popper.min.js\"></script>\n" +
                                "  <script src=\"https://cdn.staticfile.org/twitter-bootstrap/4.3.1/js/bootstrap.min.js\"></script>\n" +
                                "  <style>\n" +
                                "  /* Make the image fully responsive */\n" +
                                "  .carousel-inner img {\n" +
                                "      width: 100%;\n" +
                                "      height: 100%;\n" +
                                "  }\n" +
                                "  </style>\n" +
                                "</head>\n" +
                                "<body>\n" +
                                "\n" +
                                "<div id=\"demo\" class=\"carousel slide\" data-ride=\"carousel\">\n" +
                                " \n" +
                                "  <!-- 指示符 -->\n" +
                                "  <ul class=\"carousel-indicators\">\n" +
                                "    <li data-target=\"#demo\" data-slide-to=\"0\" class=\"active\"></li>\n" +
                                "    <li data-target=\"#demo\" data-slide-to=\"1\"></li>\n" +
                                "    <li data-target=\"#demo\" data-slide-to=\"2\"></li>\n" +
                                "  </ul>\n" +
                                " \n" +
                                "  <!-- 轮播图片 -->\n" +
                                "  <div class=\"carousel-inner\">\n" +
                                "    <div class=\"carousel-item active\">\n" +
                                "      <img src=\"https://static.runoob.com/images/mix/img_fjords_wide.jpg\">\n" +
                                "    </div>\n" +
                                "    <div class=\"carousel-item\">\n" +
                                "      <img src=\"https://static.runoob.com/images/mix/img_nature_wide.jpg\">\n" +
                                "    </div>\n" +
                                "    <div class=\"carousel-item\">\n" +
                                "      <img src=\"https://static.runoob.com/images/mix/img_mountains_wide.jpg\">\n" +
                                "    </div>\n" +
                                "  </div>\n" +
                                " \n" +
                                "  <!-- 左右切换按钮 -->\n" +
                                "  <a class=\"carousel-control-prev\" href=\"#demo\" data-slide=\"prev\">\n" +
                                "    <span class=\"carousel-control-prev-icon\"></span>\n" +
                                "  </a>\n" +
                                "  <a class=\"carousel-control-next\" href=\"#demo\" data-slide=\"next\">\n" +
                                "    <span class=\"carousel-control-next-icon\"></span>\n" +
                                "  </a>\n" +
                                " \n" +
                                "</div>\n" +
                                "<div class='container' style='margin-top: 20px;'><h1>Login Success!</h1></div>\n" +
                                "</body>\n" +
                                "</html>";

                        output.write(header.getBytes(StandardCharsets.UTF_8));
                    }
                    else
                    {
                        header += "<!DOCTYPE html>\n" +
                                "<html>\n" +
                                "<head>\n" +
                                "  <title>Bootstrap 实例</title>\n" +
                                "  <meta charset=\"utf-8\">\n" +
                                "  <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n" +
                                "  <link rel=\"stylesheet\" href=\"https://cdn.staticfile.org/twitter-bootstrap/4.3.1/css/bootstrap.min.css\">\n" +
                                "  <script src=\"https://cdn.staticfile.org/jquery/3.2.1/jquery.min.js\"></script>\n" +
                                "  <script src=\"https://cdn.staticfile.org/popper.js/1.15.0/umd/popper.min.js\"></script>\n" +
                                "  <script src=\"https://cdn.staticfile.org/twitter-bootstrap/4.3.1/js/bootstrap.min.js\"></script>\n" +
                                "</head>\n" +
                                "<body>\n" +
                                "\n" +
                                "<div class='container' style='margin-top: 20px;'><h1>Login Failed!</h1></div>\n" +
                                "</body>\n" +
                                "</html>";

                        output.write(header.getBytes(StandardCharsets.UTF_8));
                    }
                }
                else
                {
                    String errorMessage = "HTTP/1.1 200 OK\r\n" +
                            "Content-Type:text/html\r\n" +
                            "Content-Length:22\r\n" +
                            "\r\n" +
                            "<h1>Login Failed!</h1>";
                    output.write(errorMessage.getBytes());
                }
            }
        }
        catch (Exception e)
        {
            System.out.println(e.toString());
        }
        finally
        {
            if (fis != null)
            {
                fis.close();
            }
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值