11

私は、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();
    }

そして、私はHttpHandlerインターフェースのメソッドを実装して、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の軽量サーバーを完全に使用して、最初から何かを構築することに集中する必要がありますか?

助けてくれてありがとう。

4

2 に答える 2

26

ServerImplでわかるように、デフォルトのエグゼキュータはタスクを「実行」するだけです。

  157       private static class DefaultExecutor implements Executor {
  158           public void execute (Runnable task) {
  159               task.run();
  160           }
  161       }

次のように、httpServerに実際のエグゼキュータを提供する必要があります。

server.setExecutor(java.util.concurrent.Executors.newCachedThreadPool());

サーバーは並行して実行されます。注意してください。これは無制限のエグゼキュータです。スレッドの数を制限するには、Executors.newFixedThreadPoolを参照してください。

于 2013-02-06T13:08:19.823 に答える
1

同じ呼び出し元スレッドでハンドラーを実行するserver.setExecutor(null )を使用しました。この場合、サーバーを実行するメインスレッド。

次のように行を変更するだけです

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(Executors.newCachedThreadPool());
    server.start();
}
于 2019-02-25T13:55:37.787 に答える