【发布时间】:2019-02-25 21:55:37
【问题描述】:
根据我在网上找到的教程,我使用 Sun 的轻量级 HttpServer 构建了一个简单的 HttpServer。
main函数基本上是这样的:
public static void main(String[] args) throws Exception {
HttpServer server = HttpServer.create(new InetSocketAddress(8000), 0);
//Create the context for the server.
server.createContext("/", new BaseHandler());
server.setExecutor(null); // creates a default executor
server.start();
}
并且我已经实现了BaseHandler接口的方法来处理Http请求并返回响应。
static class BaseHandler implements HttpHandler {
//Handler method
public void handle(HttpExchange t) throws IOException {
//Implementation of http request processing
//Read the request, get the parameters and print them
//in the console, then build a response and send it back.
}
}
我还创建了一个通过线程发送多个请求的客户端。每个线程向服务器发送以下请求:
http://localhost:8000/[context]?int="+threadID
在每个客户端运行时,请求似乎以不同的顺序到达服务器,但它们是以串行方式提供的。
如果可能的话,我希望以并行方式处理请求。
例如,是否有可能在单独的线程中运行每个处理程序,如果可以,这样做是不是一件好事。
或者我应该完全放弃使用 Sun 的轻量级服务器并专注于从头开始构建一些东西?
感谢您的帮助。
【问题讨论】:
-
HttpServer 已经做到了。
-
这是通过设置执行器来完成的,见docs.oracle.com/javase/6/docs/api/java/util/concurrent/…
-
如果这不是一个学习项目,我建议您查看像 Apache Mina 或 Netty 这样的库。
-
感谢大家的快速回复!我会尽快调查。
标签: java httpserver