简单的 手写 服务器

服务器

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class MyHttpServer {
    //端口
    private int port = 8080;

    //接收请求的方法
    public void receiving(){
        try {
            //创建Socket服务
            ServerSocket serverSocket = new ServerSocket(port);
            //循环接收请求
            while (true){
                //获取连接对象
                Socket socket = serverSocket.accept();
                //获取连接对象的输入流
                InputStream inputStream = socket.getInputStream();
                //创建Request
                MyHttpRequest request = new MyHttpRequest(inputStream);
                //解析请求
                request.parse();
                //创建Response
                OutputStream outputStream = socket.getOutputStream();
                MyHttpResponse response = new MyHttpResponse(outputStream);
                //进行响应
                response.sendRedirect(request.getUri());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

请求

import java.io.IOException;
import java.io.InputStream;

public class MyHttpRequest {

    private InputStream inputStream;
    private String uri;

    public MyHttpRequest(InputStream inputStream) {
        this.inputStream = inputStream;
    }

    public void parse(){
        try {
            byte[] bytes = new byte[1024];
            inputStream.read(bytes);
            String request = new String(bytes);
            parseUri(request);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void parseUri(String request){
        int index1,index2;
        index1 = request.indexOf(' ');
        index2 = request.indexOf(' ',index1+1);
        uri = request.substring(index1+1,index2);
    }

    public String getUri(){
        return this.uri;
    }
}

响应

import java.io.*;

public class MyHttpResponse {

    private OutputStream outputStream;

    public MyHttpResponse(OutputStream outputStream) {
        this.outputStream = outputStream;
    }

    public void sendRedirect(String uri){
        //判断uri是否存在
        //不存在返回404
        //存在直接返回目标资源数据
        File file = new File(System.getProperty("user.dir") + "/WebContent" + uri);
        if(file.exists()){
            try {
                //返回目标资源数据
                FileInputStream fileInputStream = new FileInputStream(file);
                byte[] bytes = new byte[(int)file.length()];
                fileInputStream.read(bytes);
                String result = new String(bytes);
                String response = getResponseMessage("200", result);
                this.outputStream.write(response.getBytes());
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            try {
                //返回404
                String error = getResponseMessage("404", "404 File Not Found!");
                this.outputStream.write(error.getBytes());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public String getResponseMessage(String code,String message){
        return "HTTP/1.1 "+code+"\r\n"
                +"Content-type: text/html\r\n"
                +"Content-Length: "+message.length()
                +"\r\n"
                +"\r\n"
                +message;
    }
}

测试

public class Test {
    public static void main(String[] args) {
        System.out.println("Server startup successfully");
        MyHttpServer server = new MyHttpServer();
        server.receiving();
    }
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
手写一个 JavaWeb 服务器,需要掌握以下步骤: 1. 创建一个 ServerSocket 对象,指定服务器监听的端口号; 2. 在一个循环中,不断接收客户端的请求,每次接收到一个请求,就创建一个 Socket 对象与客户端进行连接; 3. 创建一个线程池,来处理客户端的请求。每当有一个客户端连接时,就将该客户端的请求交给线程池去处理; 4. 在线程池中,根据请求的 URL,读取对应的静态资源文件,并将其返回给客户端; 5. 如果请求的是动态资源,即需要执行 Java 代码生成内容的,那么就需要在服务器端编写对应的 Servlet。在处理请求时,根据 URL 匹配对应的 Servlet,并调用其相应的方法生成内容,并将其返回给客户端; 6. 在处理完客户端请求之后,需要关闭连接。 下面是一个简单JavaWeb 服务器的示例代码: ```java import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.OutputStream; import java.net.ServerSocket; import java.net.Socket; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class SimpleServer { private final static int PORT = 8080; private final static String WEB_ROOT = "src/main/resources/"; public static void main(String[] args) throws IOException { ServerSocket serverSocket = new ServerSocket(PORT); ExecutorService threadPool = Executors.newFixedThreadPool(10); System.out.println("Server is running at http://localhost:" + PORT); while (true) { Socket socket = serverSocket.accept(); Runnable task = () -> { try { String request = getRequest(socket.getInputStream()); String url = parseUrl(request); if (url.equals("/")) { url = "/index.html"; } String filePath = WEB_ROOT + url; File file = new File(filePath); if (file.exists() && file.isFile()) { String contentType = guessContentType(filePath); byte[] content = readFile(file); sendResponse(socket.getOutputStream(), "HTTP/1.1 200 OK", contentType, content); } else { sendResponse(socket.getOutputStream(), "HTTP/1.1 404 Not Found", "text/html", "404 Not Found".getBytes()); } } catch (IOException e) { e.printStackTrace(); } finally { try { socket.close(); } catch (IOException e) { e.printStackTrace(); } } }; threadPool.execute(task); } } private static String getRequest(java.io.InputStream input) throws IOException { byte[] buffer = new byte[1024]; int len = input.read(buffer); return new String(buffer, 0, len); } private static String parseUrl(String request) { int index1, index2; index1 = request.indexOf(' '); if (index1 != -1) { index2 = request.indexOf(' ', index1 + 1); if (index2 > index1) { return request.substring(index1 + 1, index2); } } return null; } private static byte[] readFile(File file) throws IOException { try (FileInputStream fis = new FileInputStream(file)) { byte[] buffer = new byte[fis.available()]; fis.read(buffer); return buffer; } } private static String guessContentType(String fileName) { if (fileName.endsWith(".html") || fileName.endsWith(".htm")) { return "text/html"; } else if (fileName.endsWith(".jpg") || fileName.endsWith(".jpeg")) { return "image/jpeg"; } else if (fileName.endsWith(".gif")) { return "image/gif"; } else if (fileName.endsWith(".png")) { return "image/png"; } else if (fileName.endsWith(".css")) { return "text/css"; } else if (fileName.endsWith(".js")) { return "application/javascript"; } else { return "application/octet-stream"; } } private static void sendResponse(OutputStream output, String status, String contentType, byte[] content) throws IOException { output.write((status + "\r\n").getBytes()); output.write(("Content-Type: " + contentType + "\r\n").getBytes()); output.write(("Content-Length: " + content.length + "\r\n").getBytes()); output.write("\r\n".getBytes()); output.write(content); output.flush(); } private static void sendResponse(OutputStream output, String status, String contentType, String content) throws IOException { sendResponse(output, status, contentType, content.getBytes()); } } ``` 这个示例代码实现了一个简单的静态资源服务器。当客户端请求一个 URL 时,服务器会读取对应的静态资源文件,如果找到了文件,则将其返回给客户端。如果找不到文件,则返回一个 404 Not Found 响应。在这个示例中,我们使用了线程池来处理客户端请求,通过解析 HTTP 请求报文,来获取客户端请求的 URL,然后再根据 URL 来读取对应的资源文件。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

虚构的乌托邦

如果可以请打赏鼓励

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值