我已经使用Sun的轻量级HttpServer在线发现了一个简单的HttpServer.
基本上主要功能如下:
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();
}
Run Code Online (Sandbox Code Playgroud)
我已经实现了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.
}
}
Run Code Online (Sandbox Code Playgroud)
我还创建了一个通过线程发送多个请求的客户端.每个线程将以下请求发送到服务器:
HTTP://本地主机:8000/[上下文] INT ="+线程ID
在每个客户端运行时,请求似乎以不同的顺序到达服务器,但它们以串行方式提供.
我想要实现的是,如果可能的话,以并行方式处理请求.
例如,是否可以在单独的线程中运行每个处理程序,如果是这样,那么它是否是一件好事.
或者我应该完全放弃使用Sun的轻量级服务器并从头开始关注建筑物?
谢谢你的帮助.
twi*_*uer 20
正如您在ServerImpl中看到的那样,默认执行程序只是"运行"任务:
157 private static class DefaultExecutor implements Executor {
158 public void execute (Runnable task) {
159 task.run();
160 }
161 }
Run Code Online (Sandbox Code Playgroud)
您必须为您的httpServer提供一个真正的执行程序,如下所示:
server.setExecutor(java.util.concurrent.Executors.newCachedThreadPool());
Run Code Online (Sandbox Code Playgroud)
并且您的服务器将并行运行.小心,这是一个非限制的执行者,看到Executors.newFixedThreadPool限制线程的数量.
| 归档时间: |
|
| 查看次数: |
12477 次 |
| 最近记录: |