“NanoHttpd微型服務器”使用及源碼閱讀

“NanoHttpd微型服務器”使用及源碼閱讀

NanoHttpd僅有一個Java文件的微型Http服務器實現。其方便嵌入式設備(例如:Android設備)中啓動一個本地服務器,接收客戶端本地部分請求;應用場景也非常廣泛,例如:本地代理方式播放m3u8視頻、本地代理方式加載一些加密祕鑰等。

這裏分三部分學習一個這個NanoHttpd:

  • 瞭解官方對NanoHttpd描述定義
  • 舉例NanoHttpd在Android上的使用(Android本地代理,播放Sdcard中的m3u8視頻)
  • 分析源碼實現

NanoHttpd GitHub地址:https://github.com/NanoHttpd/nanohttpd

一、NanoHttpd 官方描述

Tiny, easily embeddable HTTP server in Java.
微小的,輕量級適合嵌入式設備的Java Http服務器;
NanoHTTPD is a light-weight HTTP server designed for embedding in other applications, released under a Modified BSD licence.
NanoHTTPD是一個輕量級的、爲嵌入式設備應用設計的HTTP服務器,遵循修訂後的BSD許可協議。

核心功能描述:

  • Only one Java file, providing HTTP 1.1 support.
    僅一個Java文件,支持Http 1.1
  • No fixed config files, logging, authorization etc. (Implement by yourself if you need them. Errors are passed to java.util.logging, though.)
    沒有固定的配置文件、日誌系統、授權等等(如果你有需要需自己實現。工程中的日誌輸出,通過java.util.logging實現的)
  • Support for HTTPS (SSL).
    支持Https
  • Basic support for cookies.
    支持cookies
  • Supports parameter parsing of GET and POST methods.
    支持POST和GET 參數請求
  • Some built-in support for HEAD, POST and DELETE requests. You can easily implement/customize any HTTP method, though.
    內置支持HEAD、POST、DELETE請求,你可以方便的實現或自定義任何HTTP方法請求。
  • Supports file upload. Uses memory for small uploads, temp files for large ones.
    支持文件上傳。小文件上傳使用內存緩存,大文件使用臨時文件緩存。
  • Never caches anything.
    不緩存任何內容
  • Does not limit bandwidth, request time or simultaneous connections by default.
  • 默認不限制帶寬、請求時間 和 最大請求量
  • All header names are converted to lower case so they don't vary between browsers/clients.
    所有Header 名都被轉換爲小寫,因此不會因客戶端或瀏覽器的不同而有所差別
  • Persistent connections (Connection "keep-alive") support allowing multiple requests to be served over a single socket connection.
    支持一個socket連接服務多個長連接請求。

二、NanoHttpd在Android上的使用舉例

爲了學習NanoHttpd,做了一個簡單Demo “Android 本地代理方式播放 Sdcard中的m3u8視頻”:
Android 本地代理方式播放 Sdcard中的m3u8視頻
https://github.com/AndroidAppCodeDemo/Android_LocalM3u8Server

實現效果圖:

enter description here
注:

  • Android 本地代理方式播放 Sdcard中的m3u8視頻(使用的NanoHttpd 版本爲 2.3.1
    NanoHttpd 2.3.1版本下載
    https://github.com/NanoHttpd/nanohttpd/releases/tag/nanohttpd-project-2.3.1
  • NanoHttpd的使用,使 “本地代理方式播放Android Sdcard中的m3u8視頻” Demo實現變得很簡單,這裏不做具體介紹,有興趣的朋友可以自行下載瞭解。

下邊來主要來跟蹤學習NanoHttpd的源碼…

三、NanoHttpd源碼跟蹤學習

注:基於 NanoHttpd 2.3.1版本
NanoHttpd 2.3.1版本下載
https://github.com/NanoHttpd/nanohttpd/releases/tag/nanohttpd-project-2.3.1

NanoHTTPD大概的處理流程是:

  • 開啓一個服務端線程,綁定對應的端口,調用 ServerSocket.accept()方法進入等待狀態
  • 每個客戶端連接均開啓一個線程,執行ClientHandler.run()方法
  • 客戶端線程中,創建一個HTTPSession會話。執行HTTPSession.execute()
  • HTTPSession.execute() 中會完成 uri, method, headers, parms, files 的解析,並調用如下方法:
// 自定義服務器時,亦需要重載該方法
// 該方法傳入參數中,已解析出客戶端請求的所有數據,重載該方法進行相應的業務處理
HTTPSession.serve(String uri, Method method, Map<String, String> headers, Map<String, String> parms, Map<String, String> files)
  • 組織Response數據,並調用ChunkedOutputStream.send(outputStream)返回給客戶端

建議:
對於Http request、response 數據組織形式不是很瞭解的同學,建議自己瞭解後再閱讀NanoHTTPD源碼。
也可參考我的另一篇文章:
HTTP 協議詳解
https://xiaxl.blog.csdn.net/article/details/104541274

3.1、NanoHTTPD.start

從服務器啓動開始學習…

/**
 * Start the server. 啓動服務器
 *
 * @param timeout timeout to use for socket connections. 超時時間
 * @param daemon  start the thread daemon or not. 守護線程
 * @throws IOException if the socket is in use.
 */
public void start(final int timeout, boolean daemon) throws IOException {
    // 創建一個ServerSocket
    this.myServerSocket = this.getServerSocketFactory().create();
    this.myServerSocket.setReuseAddress(true);

    // 創建 ServerRunnable
    ServerRunnable serverRunnable = createServerRunnable(timeout);
    // 啓動一個線程監聽客戶端請求
    this.myThread = new Thread(serverRunnable);
    this.myThread.setDaemon(daemon);
    this.myThread.setName("NanoHttpd Main Listener");
    this.myThread.start();
    //
    while (!serverRunnable.hasBinded && serverRunnable.bindException == null) {
        try {
            Thread.sleep(10L);
        } catch (Throwable e) {
            // on android this may not be allowed, that's why we
            // catch throwable the wait should be very short because we are
            // just waiting for the bind of the socket
        }
    }
    if (serverRunnable.bindException != null) {
        throw serverRunnable.bindException;
    }
}

從以上代碼中,可以看到:

  • 代碼前兩行,創建一個ServerSocket
  • 開啓一個線程,執行ServerRunnable。這裏其實就是服務端啓動一個線程,用來監聽客戶端的請求,具體代碼在ServerRunnable中。

3.2、ServerRunnable.run()

@Override
public void run() {
    Log.e(TAG, "---run---");
    try {
        // bind
        myServerSocket.bind(hostname != null ? new InetSocketAddress(hostname, myPort) : new InetSocketAddress(myPort));
        hasBinded = true;
    } catch (IOException e) {
        this.bindException = e;
        return;
    }
    Log.e(TAG, "bind ok");
    do {
        try {
            Log.e(TAG, "before accept");
            // 等待客戶端連接
            final Socket finalAccept = NanoHTTPD.this.myServerSocket.accept();
            // 設置超時時間
            if (this.timeout > 0) {
                finalAccept.setSoTimeout(this.timeout);
            }
            // 服務端:輸入流
            final InputStream inputStream = finalAccept.getInputStream();
            Log.e(TAG, "asyncRunner.exec");
            // 執行客戶端 ClientHandler
            NanoHTTPD.this.asyncRunner.exec(createClientHandler(finalAccept, inputStream));
        } catch (IOException e) {
            NanoHTTPD.LOG.log(Level.FINE, "Communication with the client broken", e);
        }
    } while (!NanoHTTPD.this.myServerSocket.isClosed());
}

ServerRunnablerun()方法:

  • 調用 ServerSocket.bind 方法,綁定對應的端口
  • 調用 ServerSocket.accept() 線程進入阻塞等待狀態
  • 客戶端連接後,會執行createClientHandler(finalAccept, inputStream)創建一個ClientHandler,並開啓一個線程,執行其對應的ClientHandler.run()方法
  • 自定義服務器時,重載Response HTTPSession.serve(uri, method, headers, parms, files)方法,對客戶端的請求數據做出處理

3.3、ClientHandler.run()

@Override
public void run() {
    Log.e(TAG, "---run---");
    // 服務端 輸出流
    OutputStream outputStream = null;
    try {
        // 服務端的輸出流
        outputStream = this.acceptSocket.getOutputStream();
        // 創建臨時文件
        TempFileManager tempFileManager = NanoHTTPD.this.tempFileManagerFactory.create();
        // session 會話
        HTTPSession session = new HTTPSession(tempFileManager, this.inputStream, outputStream, this.acceptSocket.getInetAddress());
        // 執行會話
        while (!this.acceptSocket.isClosed()) {
            session.execute();
        }
    } catch (Exception e) {
        // When the socket is closed by the client,
        // we throw our own SocketException
        // to break the "keep alive" loop above. If
        // the exception was anything other
        // than the expected SocketException OR a
        // SocketTimeoutException, print the
        // stacktrace
        if (!(e instanceof SocketException && "NanoHttpd Shutdown".equals(e.getMessage())) && !(e instanceof SocketTimeoutException)) {
            NanoHTTPD.LOG.log(Level.SEVERE, "Communication with the client broken, or an bug in the handler code", e);
        }
    } finally {
        safeClose(outputStream);
        safeClose(this.inputStream);
        safeClose(this.acceptSocket);
        NanoHTTPD.this.asyncRunner.closed(this);
    }
}
  • TempFileManager臨時文件是爲了緩存客戶端Post請求的請求Body數據(如果數據較小,內存緩存;文件較大,緩存到文件中)
  • 創建一個HTTPSession會話,並執行其對應的HTTPSession.execute()方法
  • HTTPSession.execute()中會對客戶端的請求進行解析

3.4、HTTPSession.execute()


@Override
public void execute() throws IOException {
    Log.e(TAG, "---execute---");
    Response r = null;
    try {
        // Read the first 8192 bytes.
        // The full header should fit in here.
        // Apache's default header limit is 8KB.
        // Do NOT assume that a single read will get the entire header
        // at once!
        // Apache默認header限制8k
        byte[] buf = new byte[HTTPSession.BUFSIZE];
        this.splitbyte = 0;
        this.rlen = 0;
        // 客戶端輸入流
        int read = -1;
        this.inputStream.mark(HTTPSession.BUFSIZE);
        // 讀取8k的數據
        try {
            read = this.inputStream.read(buf, 0, HTTPSession.BUFSIZE);
        } catch (SSLException e) {
            throw e;
        } catch (IOException e) {
            safeClose(this.inputStream);
            safeClose(this.outputStream);
            throw new SocketException("NanoHttpd Shutdown");
        }
        if (read == -1) {
            // socket was been closed
            safeClose(this.inputStream);
            safeClose(this.outputStream);
            throw new SocketException("NanoHttpd Shutdown");
        }
        // 分割header數據
        while (read > 0) {
            this.rlen += read;
            // header
            this.splitbyte = findHeaderEnd(buf, this.rlen);
            // 找到header
            if (this.splitbyte > 0) {
                break;
            }
            // 8k中剩餘數據
            read = this.inputStream.read(buf, this.rlen, HTTPSession.BUFSIZE - this.rlen);
        }
        // header數據不足8k,跳過header數據
        if (this.splitbyte < this.rlen) {
            this.inputStream.reset();
            this.inputStream.skip(this.splitbyte);
        }
        //
        this.parms = new HashMap<String, List<String>>();
        // 清空header列表
        if (null == this.headers) {
            this.headers = new HashMap<String, String>();
        } else {
            this.headers.clear();
        }
        // 解析 客戶端請求
        // Create a BufferedReader for parsing the header.
        BufferedReader hin = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(buf, 0, this.rlen)));
        // Decode the header into parms and header java properties
        Map<String, String> pre = new HashMap<String, String>();
        decodeHeader(hin, pre, this.parms, this.headers);
        //
        if (null != this.remoteIp) {
            this.headers.put("remote-addr", this.remoteIp);
            this.headers.put("http-client-ip", this.remoteIp);
        }
        Log.e(TAG, "headers: " + headers);

        this.method = Method.lookup(pre.get("method"));
        if (this.method == null) {
            throw new ResponseException(Response.Status.BAD_REQUEST, "BAD REQUEST: Syntax error. HTTP verb " + pre.get("method") + " unhandled.");
        }
        Log.e(TAG, "method: " + method);

        this.uri = pre.get("uri");
        Log.e(TAG, "uri: " + uri);

        this.cookies = new CookieHandler(this.headers);
        Log.e(TAG, "cookies: " + this.cookies.cookies);

        String connection = this.headers.get("connection");
        Log.e(TAG, "connection: " + connection);
        boolean keepAlive = "HTTP/1.1".equals(protocolVersion) && (connection == null || !connection.matches("(?i).*close.*"));
        Log.e(TAG, "keepAlive: " + keepAlive);
        // Ok, now do the serve()

        // TODO: long body_size = getBodySize();
        // TODO: long pos_before_serve = this.inputStream.totalRead()
        // (requires implementation for totalRead())
        // 構造一個response
        r = serve(HTTPSession.this);
        // TODO: this.inputStream.skip(body_size -
        // (this.inputStream.totalRead() - pos_before_serve))

        if (r == null) {
            throw new ResponseException(Response.Status.INTERNAL_ERROR, "SERVER INTERNAL ERROR: Serve() returned a null response.");
        } else {
            String acceptEncoding = this.headers.get("accept-encoding");
            this.cookies.unloadQueue(r);
            // method
            r.setRequestMethod(this.method);
            r.setGzipEncoding(useGzipWhenAccepted(r) && acceptEncoding != null && acceptEncoding.contains("gzip"));
            r.setKeepAlive(keepAlive);

            // 發送response
            r.send(this.outputStream);
        }
        if (!keepAlive || r.isCloseConnection()) {
            throw new SocketException("NanoHttpd Shutdown");
        }
    } catch (SocketException e) {
        // throw it out to close socket object (finalAccept)
        throw e;
    } catch (SocketTimeoutException ste) {
        // treat socket timeouts the same way we treat socket exceptions
        // i.e. close the stream & finalAccept object by throwing the
        // exception up the call stack.
        throw ste;
    } catch (SSLException ssle) {
        Response resp = newFixedLengthResponse(Response.Status.INTERNAL_ERROR, NanoHTTPD.MIME_PLAINTEXT, "SSL PROTOCOL FAILURE: " + ssle.getMessage());
        resp.send(this.outputStream);
        safeClose(this.outputStream);
    } catch (IOException ioe) {
        Response resp = newFixedLengthResponse(Response.Status.INTERNAL_ERROR, NanoHTTPD.MIME_PLAINTEXT, "SERVER INTERNAL ERROR: IOException: " + ioe.getMessage());
        resp.send(this.outputStream);
        safeClose(this.outputStream);
    } catch (ResponseException re) {
        Response resp = newFixedLengthResponse(re.getStatus(), NanoHTTPD.MIME_PLAINTEXT, re.getMessage());
        resp.send(this.outputStream);
        safeClose(this.outputStream);
    } finally {
        safeClose(r);
        this.tempFileManager.clear();
    }
}
  • HTTPSession.execute() 完成了 uri, method, headers, parms, files 的解析
  • 完成解析後,調用Response serve(IHTTPSession session)方法,創建了一個Response
  • 完成Response數據組織後,這裏會調用ChunkedOutputStream.send(outputStream)方法將數據發出去。

到這裏,主要流程結束,其他細節需大家自己去用心研讀源碼了。我的Demo中增加了很多中文註釋,可以幫助大家省下一部分力氣,就這樣了

相關參考

NanoHttpd GitHub
https://github.com/NanoHttpd/nanohttpd

NanoHttpd源碼分析
https://www.iteye.com/blog/shensy-1880381

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章