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

来源:https://www.cnblogs.com/xiaxveliang/archive/2020/03/02/12395936.html
-Advertisement-
Play Games

偶然發現 ,僅僅一個Java文件,可在嵌入式設備(例:Android手機)中啟動一個本地伺服器,接收客戶端本地部分請求。 認真學習了其源碼實現,這裡按照我的學習順序寫了一篇簡單的文章(算是學習筆記吧): + 瞭解官方描述 + 寫個Demo使用一下(Android中本地代理,播放Sdcard中的m3u ...


偶然發現NanoHttpd,僅僅一個Java文件,可在嵌入式設備(例:Android手機)中啟動一個本地伺服器,接收客戶端本地部分請求。
認真學習了其源碼實現,這裡按照我的學習順序寫了一篇簡單的文章(算是學習筆記吧):

  • 瞭解官方描述
  • 寫個Demo使用一下(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許可協議。

Core

  • 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連接服務多個長連接請求。

二、Android 本地代理方式播放 Sdcard中的m3u8視頻

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

Demo實現下載
https://github.com/AndroidAppCodeDemo/Android_LocalM3u8Server

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請求數據格式

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

========== THE END ==========

wx_gzh.jpg


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 今天在三星S8上遇見一個奇葩問題 一、出現場景 + 三星手機S8 android 8.0 + targetSdkVersion 27 + 透明Activity 二、解決方案 manifest中移除 三、原因(源碼中尋找) 查看Android 8.0源碼 3.1、ActivityRecord setR ...
  • HashMap源碼來自:android 25/java/util/HashMap 一、構造方法 下麵通過跟中源碼查看: table數組初始化 介紹put(K key, V value)方法前,先簡單介紹table數組初始化 ps: 這裡預設初始化了一個數組容量為16的table數組,其中關於roun ...
  • 我們在用MAT(Memory Analyzer Tool)分析Android記憶體時,會發現大量的bitmap對象占了記憶體使用。但是很難定位究竟是哪張圖片占用了記憶體,這裡介紹一種查看bitmap的方法。 MAT、GIMP下載 MAT http://www.eclipse.org/mat/downloa ...
  • SparseArray源碼來自:android 25/java/util/SparseArray ArrayMap源碼來自:25.3.1/support compat 25.3.1/android/android.support.v4.util.ArrayMap 一、SparseArray實現源碼學 ...
  • 英文原文地址 "Memory optimization for feeds on Android" 讀後感 在Java中HashSet只能存放繼承自Objcet的對象,這中情況下“基本數據類型”轉化為繼承自Object的( 、`Long`等)會產生很多中間Object對象,占用過多的記憶體,從而引發垃 ...
  • 效果圖 實現源碼(已上傳我的GitHub): "https://github.com/xiaxveliang/GL_AUDIO_VIDEO_RECODE" 參考: "http://bigflake.com/mediacodec/EncodeAndMuxTest.java.txt" 對於以上代碼,我做 ...
  • obj文件是3D模型文件格式。由Alias|Wavefront公司為3D建模和動畫軟體"Advanced Visualizer"開發的一種標準,適合用於3D軟體模型之間的互導,也可以通過Maya讀寫。 + 只支持模型三角面數據和材質信息,無動畫功能支持; + 其中幾何信息由.obj文件提供,材質信息 ...
  • Mac下Jenkins Android打包 一、安裝tomcat a、下載tomcat http://tomcat.apache.org/ 下載完成後解壓到: b、啟動tomcat: c、驗證 二、安裝Jenkins a、下載 jenkins.war https://jenkins.io/index ...
一周排行
    -Advertisement-
    Play Games
  • 示例項目結構 在 Visual Studio 中創建一個 WinForms 應用程式後,項目結構如下所示: MyWinFormsApp/ │ ├───Properties/ │ └───Settings.settings │ ├───bin/ │ ├───Debug/ │ └───Release/ ...
  • [STAThread] 特性用於需要與 COM 組件交互的應用程式,尤其是依賴單線程模型(如 Windows Forms 應用程式)的組件。在 STA 模式下,線程擁有自己的消息迴圈,這對於處理用戶界面和某些 COM 組件是必要的。 [STAThread] static void Main(stri ...
  • 在WinForm中使用全局異常捕獲處理 在WinForm應用程式中,全局異常捕獲是確保程式穩定性的關鍵。通過在Program類的Main方法中設置全局異常處理,可以有效地捕獲並處理未預見的異常,從而避免程式崩潰。 註冊全局異常事件 [STAThread] static void Main() { / ...
  • 前言 給大家推薦一款開源的 Winform 控制項庫,可以幫助我們開發更加美觀、漂亮的 WinForm 界面。 項目介紹 SunnyUI.NET 是一個基於 .NET Framework 4.0+、.NET 6、.NET 7 和 .NET 8 的 WinForm 開源控制項庫,同時也提供了工具類庫、擴展 ...
  • 說明 該文章是屬於OverallAuth2.0系列文章,每周更新一篇該系列文章(從0到1完成系統開發)。 該系統文章,我會儘量說的非常詳細,做到不管新手、老手都能看懂。 說明:OverallAuth2.0 是一個簡單、易懂、功能強大的許可權+可視化流程管理系統。 有興趣的朋友,請關註我吧(*^▽^*) ...
  • 一、下載安裝 1.下載git 必須先下載並安裝git,再TortoiseGit下載安裝 git安裝參考教程:https://blog.csdn.net/mukes/article/details/115693833 2.TortoiseGit下載與安裝 TortoiseGit,Git客戶端,32/6 ...
  • 前言 在項目開發過程中,理解數據結構和演算法如同掌握蓋房子的秘訣。演算法不僅能幫助我們編寫高效、優質的代碼,還能解決項目中遇到的各種難題。 給大家推薦一個支持C#的開源免費、新手友好的數據結構與演算法入門教程:Hello演算法。 項目介紹 《Hello Algo》是一本開源免費、新手友好的數據結構與演算法入門 ...
  • 1.生成單個Proto.bat內容 @rem Copyright 2016, Google Inc. @rem All rights reserved. @rem @rem Redistribution and use in source and binary forms, with or with ...
  • 一:背景 1. 講故事 前段時間有位朋友找到我,說他的窗體程式在客戶這邊出現了卡死,讓我幫忙看下怎麼回事?dump也生成了,既然有dump了那就上 windbg 分析吧。 二:WinDbg 分析 1. 為什麼會卡死 窗體程式的卡死,入口門檻很低,後續往下分析就不一定了,不管怎麼說先用 !clrsta ...
  • 前言 人工智慧時代,人臉識別技術已成為安全驗證、身份識別和用戶交互的關鍵工具。 給大家推薦一款.NET 開源提供了強大的人臉識別 API,工具不僅易於集成,還具備高效處理能力。 本文將介紹一款如何利用這些API,為我們的項目添加智能識別的亮點。 項目介紹 GitHub 上擁有 1.2k 星標的 C# ...