一文讀懂 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實作效果圖:
注:
- Android 本地代理方式播放 Sdcard中的m3u8視訊(
)使用的NanoHttpd 版本為 2.3.1
- NanoHttpd的使用,使 “本地代理方式播放Android Sdcard中的m3u8視訊” Demo實作變得很簡單,這裡不做具體介紹,有興趣的朋友可以自行下載下傳了解。
下邊來主要來跟蹤學習NanoHttpd的源碼...
三、NanoHttpd源碼跟蹤學習
注:基于 NanoHttpd 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/1045412743.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);
}
}
-
臨時檔案是為了緩存用戶端Post請求的請求Body資料(如果資料較小,記憶體緩存;檔案較大,緩存到檔案中)TempFileManager
-
會話,并執行其對應的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 NanoHttpd源碼分析 https://www.iteye.com/blog/shensy-1880381= THE END =
文章首發于公衆号”CODING技術小館“,如果文章對您有幫助,可關注我的公衆号。