“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.1No 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).
支持HttpsBasic support for cookies.
支持cookiesSupports 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
實作效果圖:

注:
- 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());
}
ServerRunnable的run()方法:
- 呼叫
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 ==========

轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/28311.html
標籤:Android
上一篇:Android Q 深色主題舉例
下一篇:.obj 和 .mtl格式詳解
