自学内容网 自学内容网

java-实现一个简单的httpserver-0.6.0

2024年10月14日14:17:07—0.6.0

java-实现一个简单的httpserver-0.6.0

背景

通常写了一些接口,需要通过临时的http访问,又不需要spring这么厚重的框架

功能

  1. 设置并发
  2. 监控并发
  3. 两个get请求一个是根路径,一个是other
  4. 增加了一个post请求的方法other1

具体代码

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;

import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

public class server {
    private static AtomicInteger concurrentConnections = new AtomicInteger(0);

    public static void main(String[] args) throws IOException {
        HttpServer server = HttpServer.create(new InetSocketAddress("localhost", 8222), 0);

        // 处理根路径get请求
        server.createContext("/", new RootHandler());

        // 处理 /other 路径get请求
        server.createContext("/other", new OtherHandler());

        // 处理 /other1 路径post请求
        server.createContext("/other1", new Other1Handler());

        // 设置并发连接数
        server.setExecutor(java.util.concurrent.Executors.newFixedThreadPool(10));

        server.start();
        System.out.println("Server started on port 8000.");

        // 定期打印当前并发连接数
        new Thread(() -> {
            while (true) {
                try {
                    Thread.sleep(5000);
                    System.out.println("Current concurrent connections: " + concurrentConnections.get());
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
        }).start();
    }

    static class RootHandler implements HttpHandler {
        @Override
        public void handle(HttpExchange exchange) throws IOException {
            concurrentConnections.incrementAndGet();

            if ("GET".equals(exchange.getRequestMethod())) {
                String response = "Hello from root path!";
                exchange.sendResponseHeaders(200, response.length());
                OutputStream os = exchange.getResponseBody();
                os.write(response.getBytes());
                os.close();
                // 监控连接释放事件
                System.out.println("root Connection released");
            }

            concurrentConnections.decrementAndGet();
        }
    }

    static class OtherHandler implements HttpHandler {
        @Override
        public void handle(HttpExchange exchange) throws IOException {
            concurrentConnections.incrementAndGet();

            if ("GET".equals(exchange.getRequestMethod())) {
                String response = "This is a response for /other path.";
                exchange.sendResponseHeaders(200, response.length());
                OutputStream os = exchange.getResponseBody();
                os.write(response.getBytes());
                os.close();
            }
            // 监控连接释放事件
            System.out.println("/other Connection released");
            concurrentConnections.decrementAndGet();
        }
    }

    static class Other1Handler implements HttpHandler {
        @Override
        public void handle(HttpExchange exchange) throws IOException {
            concurrentConnections.incrementAndGet();

            if ("POST".equals(exchange.getRequestMethod())) {
                String response = "This is a response for /other1 post path.";
                exchange.sendResponseHeaders(200, response.length());
                OutputStream os = exchange.getResponseBody();
                os.write(response.getBytes());
                os.close();
            }
            // 监控连接释放事件
            System.out.println("/other Connection released");
            concurrentConnections.decrementAndGet();
        }
    }
}

打印

root Connection released
Current concurrent connections: 0
/other Connection released
root Connection released
/other Connection released
/other Connection released
/other Connection released
/other Connection released
/other Connection released
Current concurrent connections: 0
/other Connection released
/other Connection released
/other Connection released
root Connection released
Current concurrent connections: 0
Current concurrent connections: 0

原文地址:https://blog.csdn.net/m0_60688978/article/details/142877594

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!