`
默默的小熊
  • 浏览: 232841 次
社区版块
存档分类
最新评论

HttpServer源码分析

 
阅读更多

/**
 * This class implements a simple HTTP server. A HttpServer is bound to an IP address
 * and port number and listens for incoming TCP connections from clients on this address.
 * The sub-class {@link HttpsServer} implements a server which handles HTTPS requests.
 * <p>
 * One or more {@link HttpHandler} objects must be associated with a server
 * in order to process requests. Each such HttpHandler is registered
 * with a root URI path which represents the
 * location of the application or service on this server. The mapping of a handler
 * to a HttpServer is encapsulated by a {@link HttpContext} object. HttpContexts
 * are created by calling {@link #createContext(String,HttpHandler)}.
 * Any request for which no handler can be found is rejected with a 404 response.
 * Management of threads can be done external to this object by providing a
 * {@link java.util.concurrent.Executor} object. If none is provided a default
 * implementation is used.
 * <p>
 * <a name="mapping_description"></a>
 * <b>Mapping request URIs to HttpContext paths</b><p>
 * When a HTTP request is received,
 * the appropriate HttpContext (and handler) is located by finding the context
 * whose path is the longest matching prefix of the request URI's path.
 * Paths are matched literally, which means that the strings are compared
 * case sensitively, and with no conversion to or from any encoded forms.
 * For example. Given a HttpServer with the following HttpContexts configured.<p>
 * <table >
 * <tr><td><i>Context</i></td><td><i>Context path</i></td></tr>
 * <tr><td>ctx1</td><td>"/"</td></tr>
 * <tr><td>ctx2</td><td>"/apps/"</td></tr>
 * <tr><td>ctx3</td><td>"/apps/foo/"</td></tr>
 * </table>
 * <p>
 * the following table shows some request URIs and which, if any context they would
 * match with.<p>
 * <table>
 * <tr><td><i>Request URI</i></td><td><i>Matches context</i></td></tr>
 * <tr><td>"http://foo.com/apps/foo/bar"</td><td>ctx3</td></tr>
 * <tr><td>"http://foo.com/apps/Foo/bar"</td><td>no match, wrong case</td></tr>
 * <tr><td>"http://foo.com/apps/app1"</td><td>ctx2</td></tr>
 * <tr><td>"http://foo.com/foo"</td><td>ctx1</td></tr>
 * </table>
 * <p>
 * <b>Note about socket backlogs</b><p>
 * When binding to an address and port number, the application can also specify an integer
 * <i>backlog</i> parameter. This represents the maximum number of incoming TCP connections
 * which the system will queue internally. Connections are queued while they are waiting to
 * be accepted by the HttpServer. When the limit is reached, further connections may be
 * rejected (or possibly ignored) by the underlying TCP implementation. Setting the right
 * backlog value is a compromise between efficient resource usage in the TCP layer (not setting
 * it too high) and allowing adequate throughput of incoming requests (not setting it too low).
 * @since 1.6
 */

public abstract class HttpServer {

    /**
     */
    protected HttpServer () {
    }

    /**
     * creates a HttpServer instance which is initially not bound to any local address/port.
     * The HttpServer is acquired from the currently installed {@link HttpServerProvider}
     * The server must be bound using {@link #bind(InetSocketAddress,int)} before it can be used.
     * @throws IOException
     */
    public static HttpServer create () throws IOException {
        return create (null, 0);
    }

    /**
     * Create a <code>HttpServer</code> instance which will bind to the
     * specified {@link java.net.InetSocketAddress} (IP address and port number)
     *
     * A maximum backlog can also be specified. This is the maximum number of
     * queued incoming connections to allow on the listening socket.
     * Queued TCP connections exceeding this limit may be rejected by the TCP implementation.
     * The HttpServer is acquired from the currently installed {@link HttpServerProvider}
     *
     * @param addr the address to listen on, if <code>null</code> then bind() must be called
     *  to set the address
     * @param backlog the socket backlog. If this value is less than or equal to zero,
     *          then a system default value is used.
     * @throws BindException if the server cannot bind to the requested address,
     *          or if the server is already bound.
     * @throws IOException
     */

    public static HttpServer create (
        InetSocketAddress addr, int backlog
    ) throws IOException {
        HttpServerProvider provider = HttpServerProvider.provider();
        return provider.createHttpServer (addr, backlog);
    }

    /**
     * Binds a currently unbound HttpServer to the given address and port number.
     * A maximum backlog can also be specified. This is the maximum number of
     * queued incoming connections to allow on the listening socket.
     * Queued TCP connections exceeding this limit may be rejected by the TCP implementation.
     * @param addr the address to listen on
     * @param backlog the socket backlog. If this value is less than or equal to zero,
     *          then a system default value is used.
     * @throws BindException if the server cannot bind to the requested address or if the server
     *          is already bound.
     * @throws NullPointerException if addr is <code>null</code>
     */
    public abstract void bind (InetSocketAddress addr, int backlog) throws IOException;

    /**
     * Starts this server in a new background thread. The background thread
     * inherits the priority, thread group and context class loader
     * of the caller.
     */
    public abstract void start () ;

    /**
     * sets this server's {@link java.util.concurrent.Executor} object. An
     * Executor must be established before {@link #start()} is called.
     * All HTTP requests are handled in tasks given to the executor.
     * If this method is not called (before start()) or if it is
     * called with a <code>null</code> Executor, then
     * a default implementation is used, which uses the thread
     * which was created by the {@link #start()} method.
     * @param executor the Executor to set, or <code>null</code> for  default
     *          implementation
     * @throws IllegalStateException if the server is already started
     */
    public abstract void setExecutor (Executor executor);


    /**
     * returns this server's Executor object if one was specified with
     * {@link #setExecutor(Executor)}, or <code>null</code> if none was
     * specified.
     * @return the Executor established for this server or <code>null</code> if not set.
     */
    public abstract Executor getExecutor () ;

    /**
     * stops this server by closing the listening socket and disallowing
     * any new exchanges from being processed. The method will then block
     * until all current exchange handlers have completed or else when
     * approximately <i>delay</i> seconds have elapsed (whichever happens
     * sooner). Then, all open TCP connections are closed, the background
     * thread created by start() exits, and the method returns.
     * Once stopped, a HttpServer cannot be re-used. <p>
     *
     * @param delay the maximum time in seconds to wait until exchanges have finished.
     * @throws IllegalArgumentException if delay is less than zero.
     */
    public abstract void stop (int delay);

    /**
     * Creates a HttpContext. A HttpContext represents a mapping from a
     * URI path to a exchange handler on this HttpServer. Once created, all requests
     * received by the server for the path will be handled by calling
     * the given handler object. The context is identified by the path, and
     * can later be removed from the server using this with the {@link #removeContext(String)} method.
     * <p>
     * The path specifies the root URI path for this context. The first character of path must be
     * '/'. <p>
     * The class overview describes how incoming request URIs are <a href="#mapping_description">mapped</a>
     * to HttpContext instances.
     * @param path the root URI path to associate the context with
     * @param handler the handler to invoke for incoming requests.
     * @throws IllegalArgumentException if path is invalid, or if a context
     *          already exists for this path
     * @throws NullPointerException if either path, or handler are <code>null</code>
     */
    public abstract HttpContext createContext (String path, HttpHandler handler) ;

    /**
     * Creates a HttpContext without initially specifying a handler. The handler must later be specified using
     * {@link HttpContext#setHandler(HttpHandler)}.  A HttpContext represents a mapping from a
     * URI path to an exchange handler on this HttpServer. Once created, and when
     * the handler has been set, all requests
     * received by the server for the path will be handled by calling
     * the handler object. The context is identified by the path, and
     * can later be removed from the server using this with the {@link #removeContext(String)} method.
     * <p>
     * The path specifies the root URI path for this context. The first character of path must be
     * '/'. <p>
     * The class overview describes how incoming request URIs are <a href="#mapping_description">mapped</a>
     * to HttpContext instances.
     * @param path the root URI path to associate the context with
     * @throws IllegalArgumentException if path is invalid, or if a context
     *          already exists for this path
     * @throws NullPointerException if path is <code>null</code>
     */
    public abstract HttpContext createContext (String path) ;

    /**
     * Removes the context identified by the given path from the server.
     * Removing a context does not affect exchanges currently being processed
     * but prevents new ones from being accepted.
     * @param path the path of the handler to remove
     * @throws IllegalArgumentException if no handler corresponding to this
     *          path exists.
     * @throws NullPointerException if path is <code>null</code>
     */
    public abstract void removeContext (String path) throws IllegalArgumentException ;

    /**
     * Removes the given context from the server.
     * Removing a context does not affect exchanges currently being processed
     * but prevents new ones from being accepted.
     * @param context the context to remove
     * @throws NullPointerException if context is <code>null</code>
     */
    public abstract void removeContext (HttpContext context) ;

    /**
     * returns the address this server is listening on
     * @return the address/port number the server is listening on
     */
    public abstract InetSocketAddress getAddress() ;
}
 
分享到:
评论

相关推荐

    libuv-httpserver-源码.rar

    总结,libuv-httpserver源码分析让我们深入了解了如何利用libuv构建高性能的HTTP服务器。通过对事件循环、连接管理和请求处理等核心模块的深入学习,我们可以更好地理解和应用libuv库,从而开发出更高效的网络应用...

    http server源码实例

    通过分析和理解"SimpleHttpServer"源码,开发者不仅可以掌握HTTP服务器的基础运作机制,还能为自定义的网络应用打下坚实的基础。对于进一步学习Web开发、网络编程或者服务器端架构设计都有极大的帮助。

    apache+server源码分析+源码+内存池内幕

    此外,源码分析还能帮助我们理解Apache如何处理各种HTTP特性,如重定向、缓存、URL映射等。对于想要成为优秀Web开发者或系统管理员的人来说,这是一个不可多得的学习资源。通过阅读和理解源码,你不仅能提升技术能力...

    python-HTTP-[requests+httpServer].zip

    "requests"和"httpServer"是Python中处理HTTP请求和构建HTTP服务器的两个关键库。 "requests"库是Python中最流行的HTTP客户端库,它使得发送HTTP请求变得简单直观。通过requests库,你可以方便地执行GET、POST、PUT...

    Jetty源码分析.pdf

    ### Jetty源码分析知识点概览 #### 一、Jetty简介与特点 - **Jetty**是一款**100%纯Java编写**的轻量级Web服务器与Servlet容器,与Tomcat等其他流行的Web服务器相比,Jetty以其**体积小、启动快**而著称。 - **...

    lvs源码分析 ipvs源码分析

    源码分析可以帮助我们了解内部的工作机制,包括连接管理、协议处理、数据包发送等关键流程,从而更好地定制和调试系统,提高服务的效率和可靠性。 **均衡调度算法**: LVS提供了多种调度算法,如轮询(Round Robin...

    一个完整的WEB SERVER源码

    【标题】中的“一个完整的WEB SERVER源码”指的是包含了实现Web服务器功能的全部源代码,这对于想要学习或开发Web服务器的人来说是一份宝贵的参考资料。Web服务器是互联网基础设施的关键组成部分,它接收HTTP请求,...

    一套优秀的基于C#开发的 HTTP web server 类库源码及例子程序

    "一套优秀的基于C#开发的 HTTP web server 类库源码及例子程序" 这个标题表明我们正在讨论的是一个使用C#编程语言编写的HTTP Web服务器实现。这里的“类库”指的是一个可重用的代码集合,用于创建Web服务器,而...

    Lighttpd源码分析

    为了确保服务器的高效性和安全性,源码分析中还应该注意服务器对资源的管理(如内存使用和文件描述符的管理)以及对安全机制的实现(如防止HTTP头部注入、限制请求大小等)。 综上所述,Lighttpd的源码分析涵盖多个...

    jetty嵌入式Httpserver

    关于源码分析,Jetty的源代码结构清晰,适合学习和定制。通过阅读源码,我们可以深入理解其内部工作流程,比如请求处理链路、线程池管理、会话管理等高级特性。对于开发者来说,这是一个提升技能的好途径。 在开发...

    tomcat6源码分析

    《Tomcat6源码分析——深入理解Web服务器的运行机制》 Tomcat6作为Apache软件基金会的Jakarta项目的一部分,是一款广泛使用的Java Servlet容器,它实现了Java Servlet和JavaServer Pages(JSP)规范,为开发和部署...

    boa-0.94.13 webserver源码

    boa-0.94.13 Web服务器源码分析与配置指南 Boa是一款轻量级的、开源的Web服务器,适用于嵌入式系统或个人项目。版本0.94.13是其历史版本之一,尽管不如现代的Apache、Nginx等服务器功能强大,但在某些特定场景下,...

    zabbix源码分析

    源码分析应了解Agent如何注册监控项,如何与Server通信,以及数据封装和传输的过程。 3. **Server处理流程** Zabbix Server接收并处理Agent发送的数据,进行异常检测、触发器评估,并将结果存储到数据库中。源码...

    ZLMediaKit源码分析

    《ZLMediaKit源码分析》 ZLMediaKit是一个开源的媒体服务器框架,它主要用于音视频流的推送和播放,支持RTMP、HLS、HTTP-FLV等多种协议。本文将深入分析其架构和主要模块,以帮助读者理解其工作原理。 1. 引言 ...

    tomcat架构的源码分析

    ### Tomcat架构的源码分析 #### 一、Tomcat的架构概述 Tomcat作为一款广泛使用的开源Java Servlet容器,其内部架构设计简洁而高效。本文档将对Tomcat的架构进行详细介绍,并从源码层面深入分析其核心组成部分。...

    goahead源码分析

    GoAhead是一款轻量级的嵌入式Web服务器,它的源码分析主要涉及以下几个核心概念和流程: 1. **主函数main()**: - `main()`是程序的入口点,负责初始化整个Web服务器。 - 它调用`websOpenServer()`来启动Web...

    c# socket编程实例一 FTPserver源码

    源码分析: 1. **初始化Socket**:首先,服务器端需要创建一个Socket对象并绑定到特定的IP地址和端口号,通常使用`Bind()`方法。然后,通过调用`Listen()`设置服务器监听状态,等待客户端连接。 2. **接受连接**:...

    Http.rar_C http server_c# http_http c#_http c++_http server

    标题中的"Http.rar_C http server_c# http_http c#_http c++_http server"表明这是一个关于HTTP服务器的资源...通过阅读和分析这些源码,可以学习到如何从头开始构建一个简单的HTTP服务器,并了解如何处理并发请求。

    VLC源码分析

    VLC 源码分析 VLC(Video Lan Client)是开源、跨平台的视频播放器,支持大量的音视频传输、封装和编码格式,并具有丰富的功能特性。下面是对 VLC 源码分析的知识点: 1. VLC 简介:VLC 是一个开源的、跨平台的...

    Mina2.0 example HttpServer

    本篇文章将深入探讨Mina2.0的一个核心应用场景——HttpServer,通过分析其源码,帮助读者更好地理解和运用这一工具。 Apache Mina是一个Java框架,它简化了开发高性能和高并发网络应用程序的工作。Mina提供了一种...

Global site tag (gtag.js) - Google Analytics