在最近的項目中因為要用android作為一個伺服器去做一個實時接收資料的功能,是以這個時候就要去做一個android本地的微型伺服器。
那麼此時我首先想到了spring boot,因為他是一個伺服器的架構。但是實際上我們根本用不到這麼大型的伺服器架構,配置這些都太麻煩。是以,我又找到了ijetty、nanohttpd和androidasync這三個架構,都是比較微型的,适用于android的。
經過對比,ijetty使用起來過于複雜,而且會莫名其妙的報一些不太容易解決的問題,是以,舍棄掉了。
因為沒仔細深究ijetty,是以就重點放到nanohttpd和androidasync;
那麼就先來說下兩個的優缺點:
1.nanohttpd是bio為底層封裝的架構,而androidasync是nio為底層封裝的,其他的是一樣的,而且其實androidasync是仿照nanohttpd架構寫的。是以,一定意義上來說,androidasync是nanohttpd的優化版,當然也要看具體應用場景辣。
2.nanohttpd隻能用于httpserver,但是androidasync除了httpserver的應用還能用在websocket、httpclient等方面,其中從androidasync中脫離出來的ion的庫也是比較有名的。
3.nanohttpd底層處理包含的傳回狀态碼(例如: 200、300、400、500等)比較多;但是經過筆者閱讀androidasync的源碼發現,androidasync底層封裝傳回的狀态碼隻有兩種:200、404,正好筆者發現了這個坑(下面會講到,options的例子)
下面看一下具體使用方法吧。
1.先說nanohttpd:
因為nanohttpd的架構實際就是一個單檔案,可以直接去github上下載下傳,下載下傳位址
有了下載下傳的檔案,那麼就可以繼承這個檔案寫一個類,具體如下:
public class httpserver extends nanohttpd {
private static final string tag = "httpserver";
public static final string default_show_page = "index.html";
public static final int default_port = 9511;//此參數随便定義,最好定義1024-65535;1-1024是系統常用端口,1024-65535是非系統端口
public enum status implements response.istatus {
request_error(500, "請求失敗"),
request_error_api(501, "無效的請求接口"),
request_error_cmd(502, "無效指令");
private final int requeststatus;
private final string description;
status(int requeststatus, string description) {
this.requeststatus = requeststatus;
this.description = description;
}
@override
public string getdescription() {
return description;
public int getrequeststatus() {
return requeststatus;
}
public httpserver() {//初始化端口
super(default_port);
@override
public response serve(ihttpsession session) {
string uri = session.geturi();
map<string, string> headers = session.getheaders();
//接收不到post參數的問題, http://blog.csdn.net/obguy/article/details/53841559
try {
session.parsebody(new hashmap<string, string>());
} catch (ioexception e) {
e.printstacktrace();
} catch (responseexception e) {
map<string, string> parms = session.getparms();
logutil.d(tag, uri);
//判斷uri的合法性,自定義方法,這個是判斷是否是接口的方法
if (checkuri(uri)) {
// 針對的是接口的處理
if (headers != null) {
logutil.d(tag, headers.tostring());
}
if (parms != null) {
logutil.d(tag, parms.tostring());
if (stringutil.isempty(uri)) {
throw new runtimeexception("無法擷取請求位址");
if (method.options.equals(session.getmethod())) {
logutil.d(tag, "options探測性請求");
return addheaderresponse(response.status.ok);
switch (uri) {
case "/test": {//接口2
//此方法包括了封裝傳回的接口請求資料和處理異常以及跨域
return getxxx(parms);
}
default: {
return addheaderresponse(status.request_error_api);
} else {
//針對的是靜态資源的處理
string filepath = getfilepath(uri); // 根據url擷取檔案路徑
if (filepath == null) {
logutil.d(tag, "sd卡沒有找到");
return super.serve(session);
file file = new file(filepath);
if (file != null && file.exists()) {
logutil.d(tag, "file path = " + file.getabsolutepath());
//根據檔案名傳回mimetype: image/jpg, video/mp4, etc
string mimetype = getmimetype(filepath);
response res = null;
inputstream is = new fileinputstream(file);
res = newfixedlengthresponse(response.status.ok, mimetype, is, is.available());
//下面是跨域的參數(因為一般要和h5聯調,是以最好設定一下)
response.addheader("access-control-allow-headers", allowheaders);
response.addheader("access-control-allow-methods", "get, post, put, delete, head");
response.addheader("access-control-allow-credentials", "true");
response.addheader("access-control-allow-origin", "*");
response.addheader("access-control-max-age", "" + 42 * 60 * 60);
return res;
} else {
logutil.d(tag, "file path = " + file.getabsolutepath() + "的資源不存在");
}
} catch (exception e) {
//自己封裝的傳回請求
return addheaderrespose(status.request_error);
根據上面的例子,主要說以下幾點: 1)請求都能接收到,無論post還是get,或者是其他請求,如果需要過濾則自己去處理;
2)注意上面處理的接收不到post參數的問題,已經給了參考連結在代碼注釋中,請查閱;
3)如果請求中既有接口又有靜态資源(例如html),那注意區分兩種請求,例如可以用uri去識别;當然傳回都可以用流的形式,都可以調用api方法newfixedlengthresponse();
4)筆者建議,最好處理一下跨域的問題,因為是android有可能和h5聯調,是以設定了跨域以後比較友善調試,當然某些場景也可以忽略,看個人需求;方法已經在以上代碼中寫了;
5)當然最後最重要的一點肯定是開啟和關閉的代碼了:
/**
* 開啟本地網頁點歌的服務
*/
public static void startlocalchoosemusicserver() {
if (httpserver == null) {
httpserver = new httpserver();
try {
// 啟動web服務
if (!httpserver.isalive()) {
httpserver.start();
log.i(tag, "the server started.");
} catch (exception e) {
httpserver.stop();
log.e(tag, "the server could not start. e = " + e.tostring());
}
* 關閉本地服務
public static void quitchoosemusicserver() {
if (httpserver != null) {
if (httpserver.isalive()) {
httpserver.stop();
log.d(tag, "關閉區域網路點歌的服務");
2再看一下androidasync: 這個架構就比較有意思了,功能也多,本文直說httpserver方面的相關知識,其餘按下不表。
老規矩,先說用法: 在gradle中加入:
dependencies {
compile 'com.koushikdutta.async:androidasync:2.2.1'
代碼示例:(此處沒有處理跨域,如果需要的話,請根據上一個例子去處理)
public class niohttpserver implements httpserverrequestcallback {
private static final string tag = "niohttpserver";
private static niohttpserver minstance;
public static int port_listen_defalt = 5000;
asynchttpserver server = new asynchttpserver();
public static niohttpserver getinstance() {
if (minstance == null) {
// 增加類鎖,保證隻初始化一次
synchronized (niohttpserver.class) {
if (minstance == null) {
minstance = new niohttpserver();
return minstance;
//仿照nanohttpd的寫法
public static enum status {
request_ok(200, "請求成功"),
request_error_cmd(502, "無效指令"),
request_error_deviceid(503, "不比對的裝置id"),
request_error_env(504, "不比對的服務環境");
/**
* 開啟本地服務
public void startserver() {
//如果有其他的請求方式,例如下面一行代碼的寫法
server.addaction("options", "[\\d\\d]*", this);
server.get("[\\d\\d]*", this);
server.post("[\\d\\d]*", this);
server.listen(port_listen_defalt);
public void onrequest(asynchttpserverrequest request, asynchttpserverresponse response) {
log.d(tag, "進來了,哈哈");
string uri = request.getpath();
//這個是擷取header參數的地方,一定要謹記哦
multimap headers = request.getheaders().getmultimap();
if (checkuri(uri)) {// 針對的是接口的處理
//注意:這個地方是擷取post請求的參數的地方,一定要謹記哦
multimap parms = (( asynchttprequestbody<multimap>)request.getbody()).get();
if (headers != null) {
logutil.d(tag, headers.tostring());
if (parms != null) {
logutil.d(tag, "parms = " + parms.tostring());
if (stringutil.isempty(uri)) {
throw new runtimeexception("無法擷取請求位址");
if ("options".tolowercase().equals(request.getmethod().tolowercase())) {
logutil.d(tag, "options探測性請求");
addcorsheaders(status.request_ok, response);
return;
switch (uri) {
} else {
// 針對的是靜态資源的處理
string filepath = getfilepath(uri); // 根據url擷取檔案路徑
if (filepath == null) {
logutil.d(tag, "sd卡沒有找到");
response.send("sd卡沒有找到");
file file = new file(filepath);
if (file != null && file.exists()) {
log.d(tag, "file path = " + file.getabsolutepath());
response.sendfile(file);//和nanohttpd不一樣的地方
log.d(tag, "file path = " + file.getabsolutepath() + "的資源不存在");
根據上面的例子,主要說以下幾點:{大概說的就是api用法啊這一類的}
1)例如:server.addaction(“options”, “[\d\d]“, this)是通用的過濾請求的方法。第一個參數是請求的方法,例如用“options”、“delete”、“post”、“get”等(注意用大寫),第二個參數是過濾uri的正規表達式,此處是過濾所有的uri,第三個是回調參數。server.post(“[\d\d]“, this)、server.get(“[\d\d]*”, this)這個是上一個方法的特例。server.listen(port_listen_defalt)這個是監聽端口;
2) request.getheaders().getmultimap()
這個是擷取header參數的地方,一定要謹記哦;
3)(( asynchttprequestbody<multimap>)request.getbody()).get()這個地方是擷取post請求的參數的地方;
4)擷取靜态資源的代碼是在回調方法onresponse的else中,例子如上。
5)說一下options的坑點,因為androidasync這個架構中封裝的傳回http的狀态碼隻有兩種,假如過濾方法中沒有包含例如options的請求方法,實際上傳回給用戶端的http狀态碼是400,而反映到浏覽器的報錯資訊竟然是跨域的問題,找了很久才找到,請注意。
總結:
1)同一個頁面:
nanohttpd耗時:1.4s
androidasync耗時:1.4s
但是在第二次進去的時候,androidasync的耗時明顯比第一個少了,筆者猜測是因為androidasync底層做了一些處理。
2)從api分析的話,nanohttpd的用法比較友善,擷取傳遞的參數那些的api比較好用;androidasync的api就相對來說要複雜一些,例如params的擷取。
3)從場景來分析的話,如果需要并發量高的需求,一定要用androidasync;但是如果不需要的話,那就再具體分析。
本文作者:佚名
來源:51cto