Path: blob/master/src/jdk.httpserver/share/classes/com/sun/net/httpserver/HttpServer.java
41159 views
/*1* Copyright (c) 2005, 2020, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425package com.sun.net.httpserver;2627import com.sun.net.httpserver.spi.HttpServerProvider;2829import java.io.IOException;30import java.net.BindException;31import java.net.InetSocketAddress;32import java.util.concurrent.Executor;3334/**35* This class implements a simple HTTP server. A {@code HttpServer} is bound to an IP address36* and port number and listens for incoming TCP connections from clients on this address.37* The sub-class {@link HttpsServer} implements a server which handles HTTPS requests.38*39* <p>One or more {@link HttpHandler} objects must be associated with a server40* in order to process requests. Each such {@code HttpHandler} is registered with41* a root URI path which represents the location of the application or service42* on this server. The mapping of a handler to a {@code HttpServer} is43* encapsulated by a {@link HttpContext} object. HttpContexts are created by44* calling {@link #createContext(String,HttpHandler)}.45* Any request for which no handler can be found is rejected with a 404 response.46* Management of threads can be done external to this object by providing a47* {@link java.util.concurrent.Executor} object. If none is provided a default48* implementation is used.49*50* <p> <a id="mapping_description"></a> <b>Mapping request URIs to HttpContext paths</b>51*52* <p>When a HTTP request is received, the appropriate {@code HttpContext}53* (and handler) is located by finding the context whose path is the longest54* matching prefix of the request URI's path. Paths are matched literally,55* which means that the strings are compared case sensitively, and with no56* conversion to or from any encoded forms. For example, given a {@code HttpServer}57* with the following HttpContexts configured:58*59* <table class="striped"><caption style="display:none">description</caption>60* <thead>61* <tr>62* <th scope="col"><i>Context</i></th>63* <th scope="col"><i>Context path</i></th>64* </tr>65* </thead>66* <tbody>67* <tr><th scope="row">ctx1</th><td>"/"</td></tr>68* <tr><th scope="row">ctx2</th><td>"/apps/"</td></tr>69* <tr><th scope="row">ctx3</th><td>"/apps/foo/"</td></tr>70* </tbody>71* </table>72*73* <p>The following table shows some request URIs and which, if any context they would74* match with:75* <table class="striped"><caption style="display:none">description</caption>76* <thead>77* <tr>78* <th scope="col"><i>Request URI</i></th>79* <th scope="col"><i>Matches context</i></th>80* </tr>81* </thead>82* <tbody>83* <tr><th scope="row">"http://foo.com/apps/foo/bar"</th><td>ctx3</td></tr>84* <tr><th scope="row">"http://foo.com/apps/Foo/bar"</th><td>no match, wrong case</td></tr>85* <tr><th scope="row">"http://foo.com/apps/app1"</th><td>ctx2</td></tr>86* <tr><th scope="row">"http://foo.com/foo"</th><td>ctx1</td></tr>87* </tbody>88* </table>89*90* <p><b>Note about socket backlogs</b>91*92* <p>When binding to an address and port number, the application can also93* specify an integer <i>backlog</i> parameter. This represents the maximum94* number of incoming TCP connections which the system will queue internally.95* Connections are queued while they are waiting to be accepted by the96* {@code HttpServer}. When the limit is reached, further connections may be97* rejected (or possibly ignored) by the underlying TCP implementation. Setting98* the right backlog value is a compromise between efficient resource usage in99* the TCP layer (not setting it too high) and allowing adequate throughput of100* incoming requests (not setting it too low).101*102* @since 1.6103*/104105public abstract class HttpServer {106107/**108* Constructor for subclasses to call.109*/110protected HttpServer() {111}112113/**114* Creates a {@code HttpServer} instance which is initially not bound to any115* local address/port. The {@code HttpServer} is acquired from the currently116* installed {@link HttpServerProvider}. The server must be bound using117* {@link #bind(InetSocketAddress,int)} before it can be used.118*119* @throws IOException if an I/O error occurs120* @return an instance of {@code HttpServer}121*/122public static HttpServer create() throws IOException {123return create (null, 0);124}125126/**127* Create a {@code HttpServer} instance which will bind to the128* specified {@link java.net.InetSocketAddress} (IP address and port number).129*130* A maximum backlog can also be specified. This is the maximum number of131* queued incoming connections to allow on the listening socket.132* Queued TCP connections exceeding this limit may be rejected by the TCP133* implementation. The {@code HttpServer} is acquired from the currently134* installed {@link HttpServerProvider}135*136* @param addr the address to listen on, if {@code null} then137* {@link #bind(InetSocketAddress, int)} must be called to set138* the address139* @param backlog the socket backlog. If this value is less than or equal to zero,140* then a system default value is used141* @throws IOException if an I/O error occurs142* @throws BindException if the server cannot bind to the requested address,143* or if the server is already bound144* @return an instance of {@code HttpServer}145*/146147public static HttpServer create(InetSocketAddress addr, int backlog) throws IOException {148HttpServerProvider provider = HttpServerProvider.provider();149return provider.createHttpServer (addr, backlog);150}151152/**153* Binds a currently unbound {@code HttpServer} to the given address and154* port number. A maximum backlog can also be specified. This is the maximum155* number of queued incoming connections to allow on the listening socket.156* Queued TCP connections exceeding this limit may be rejected by the TCP157* implementation.158*159* @param addr the address to listen on160* @param backlog the socket backlog. If this value is less than or equal to161* zero, then a system default value is used162* @throws BindException if the server cannot bind to the requested address163* or if the server is already bound164* @throws NullPointerException if addr is {@code null}165*/166public abstract void bind(InetSocketAddress addr, int backlog) throws IOException;167168/**169* Starts this server in a new background thread. The background thread170* inherits the priority, thread group and context class loader171* of the caller.172*/173public abstract void start();174175/**176* Sets this server's {@link java.util.concurrent.Executor} object. An177* {@code Executor} must be established before {@link #start()} is called.178* All HTTP requests are handled in tasks given to the executor.179* If this method is not called (before {@link #start()}) or if it is called180* with a {@code null Executor}, then a default implementation is used,181* which uses the thread which was created by the {@link #start()} method.182*183* @param executor the {@code Executor} to set, or {@code null} for default184* implementation185* @throws IllegalStateException if the server is already started186*/187public abstract void setExecutor(Executor executor);188189190/**191* Returns this server's {@code Executor} object if one was specified with192* {@link #setExecutor(Executor)}, or {@code null} if none was specified.193*194* @return the {@code Executor} established for this server or {@code null} if not set.195*/196public abstract Executor getExecutor() ;197198/**199* Stops this server by closing the listening socket and disallowing200* any new exchanges from being processed. The method will then block201* until all current exchange handlers have completed or else when202* approximately <i>delay</i> seconds have elapsed (whichever happens203* sooner). Then, all open TCP connections are closed, the background204* thread created by {@link #start()} exits, and the method returns.205* Once stopped, a {@code HttpServer} cannot be re-used.206*207* @param delay the maximum time in seconds to wait until exchanges have finished208* @throws IllegalArgumentException if delay is less than zero209*/210public abstract void stop(int delay);211212/**213* Creates a {@code HttpContext}. A {@code HttpContext} represents a mapping214* from a URI path to a exchange handler on this {@code HttpServer}. Once215* created, all requests received by the server for the path will be handled216* by calling the given handler object. The context is identified by the217* path, and can later be removed from the server using this with the218* {@link #removeContext(String)} method.219*220* <p> The path specifies the root URI path for this context. The first221* character of path must be '/'.222*223* <p>The class overview describes how incoming request URIs are224* <a href="#mapping_description">mapped</a> to HttpContext instances.225*226* @apiNote The path should generally, but is not required to, end with '/'.227* If the path does not end with '/', eg such as with {@code "/foo"} then228* this would match requests with a path of {@code "/foobar"} or229* {@code "/foo/bar"}.230*231* @param path the root URI path to associate the context with232* @param handler the handler to invoke for incoming requests233* @throws IllegalArgumentException if path is invalid, or if a context234* already exists for this path235* @throws NullPointerException if either path, or handler are {@code null}236* @return an instance of {@code HttpContext}237*/238public abstract HttpContext createContext(String path, HttpHandler handler);239240/**241* Creates a HttpContext without initially specifying a handler. The handler242* must later be specified using {@link HttpContext#setHandler(HttpHandler)}.243* A {@code HttpContext} represents a mapping from a URI path to an exchange244* handler on this {@code HttpServer}. Once created, and when the handler has245* been set, all requests received by the server for the path will be handled246* by calling the handler object. The context is identified by the path, and247* can later be removed from the server using this with the248* {@link #removeContext(String)} method.249*250* <p>The path specifies the root URI path for this context. The first character of path must be251* '/'.252*253* <p>The class overview describes how incoming request URIs are254* <a href="#mapping_description">mapped</a> to {@code HttpContext} instances.255*256* @apiNote The path should generally, but is not required to, end with '/'.257* If the path does not end with '/', eg such as with {@code "/foo"} then258* this would match requests with a path of {@code "/foobar"} or259* {@code "/foo/bar"}.260*261* @param path the root URI path to associate the context with262* @throws IllegalArgumentException if path is invalid, or if a context263* already exists for this path264* @throws NullPointerException if path is {@code null}265* @return an instance of {@code HttpContext}266*/267public abstract HttpContext createContext(String path);268269/**270* Removes the context identified by the given path from the server.271* Removing a context does not affect exchanges currently being processed272* but prevents new ones from being accepted.273*274* @param path the path of the handler to remove275* @throws IllegalArgumentException if no handler corresponding to this276* path exists.277* @throws NullPointerException if path is {@code null}278*/279public abstract void removeContext(String path) throws IllegalArgumentException;280281/**282* Removes the given context from the server.283* Removing a context does not affect exchanges currently being processed284* but prevents new ones from being accepted.285*286* @param context the context to remove287* @throws NullPointerException if context is {@code null}288*/289public abstract void removeContext(HttpContext context);290291/**292* Returns the address this server is listening on293*294* @return the {@code InetSocketAddress} the server is listening on295*/296public abstract InetSocketAddress getAddress();297}298299300