利用Java Socket编写一个简单的Web服务器

1-2 利用Java Socket编写一个简单的Web服务器,具体如下:
(1)、使用 ServerSocket 监听某一端口,然后等待连接获取 Socket对象;
(2)、创建一个类 HttpServer 继承 java.lang.Thread 类,重写 run()方法,执行浏览器请求;
(3)、获得浏览器请求,解析资源文件路径;
(4)、读取资源文件,响应给浏览器;
(5)、浏览器地址栏输入: http://localhost:8000/index.html;
(6)、效果如下:

代码:

在这里插入图片描述
启动类

public class RunApp {
    public static void main(String[] args) {
        new WebServer().startServer(8000);
    }
}
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class WebServer {
    //
    public void startServer(int port) {
        try {
            @SuppressWarnings("resource")
            ServerSocket serverSocket = new ServerSocket(port);
            while (true) {
                //服务器套接字
                Socket socket = serverSocket.accept();
                new HttpServer(socket).start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;

/**
 * @description: 使用socket 实现 web服务器 --- 具体执行读写操作的。
 *
 */
public class HttpServer extends Thread {
    /**
     * web资源根路径
     */
    /**
     * 输入流对象,读取浏览器请求
     */
    private InputStream input;

    /**
     * 输出流对象,响应内容给浏览器
     */
    private OutputStream out;

    /**
     * @description:初始化socket对象,获取对应 输入,输出流
     * @param socket
     */
    public HttpServer(Socket socket) {
        try {
            input = socket.getInputStream();
            out = socket.getOutputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 多线程方法调用
     */
    @Override
    public void run() {
        String filePath = read();
        response(filePath);
    }

    /**
     * @description: 读取资源文件,响应给浏览器。
     * @param:@param filePath  资源文件路径
     *
     *
     */
    private void response(String filePath) {
        //获得项目下的路径
        String path = System.getProperty("user.dir");
        File file = new File(path + filePath);
        if (!filePath.equals("/")) {
            if (file.exists()) {
                // 1、资源存在,读取资源
                try {
                    //做个判断是否为空
                    BufferedReader reader = new BufferedReader(new FileReader(file));
                    System.out.println("reader" + reader);
                    StringBuffer sb = new StringBuffer();
                    String line = null;
                    while ((line = reader.readLine()) != null) {
                        sb.append(line).append("\r\n");
                    }
                    StringBuffer result = new StringBuffer();
                    result.append("HTTP /1.1 200 ok \r\n");
                    result.append("Content-Type:text/html \r\n");
                    result.append("Content-Length:" + file.length() + "\r\n");
                    result.append("\r\n" + sb.toString());
                    //System.out.println("result=="+result);
                    out.write(result.toString().getBytes());
                    out.flush();
                    out.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }

            } else {
                // 2、资源不存在,提示 file not found
                StringBuffer error = new StringBuffer();
                error.append("HTTP /1.1 400 file not found \r\n");
                error.append("Content-Type:text/html \r\n");
                error.append("Content-Length:20 \r\n").append("\r\n");
                error.append("<h1 >File Not Found..</h1>");
                try {
                    out.write(error.toString().getBytes());
                    out.flush();
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }else {
            //默认界面
            StringBuffer error = new StringBuffer();
            error.append("HTTP /1.1 200 hello word \r\n");
            error.append("Content-Type:text/html \r\n");
            error.append("Content-Length:20 \r\n").append("\r\n");
            error.append("<h1 >hello word</h1>");
            try {
                out.write(error.toString().getBytes());
                out.flush();
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     *
     * @description:解析资源文件路径
     * @example: GET /index.html HTTP/1.1
     *
     *
     */
    private String read() {
        BufferedReader reader = new BufferedReader(new InputStreamReader(input));
        try {
            // 读取请求头, 如:GET /index.html HTTP/1.1
            String readLine = reader.readLine();
            String[] split = readLine.split(" ");
            if (split.length != 3) {
                return null;
            }
            //System.out.println(readLine);
            return split[1];
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}

html(放在根路径)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>there is title</title>
</head>
<body>
    <h1>Hello World! this is my webserver!</h1>
</body>
</html>

运行截图:

在这里插入图片描述

  • 24
    点赞
  • 89
    收藏
    觉得还不错? 一键收藏
  • 18
    评论
评论 18
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值