架設HttpServer - NanoHttpd

NanoHttpd是一個輕量級的Http Server,可在本地端接收Http Client所傳來的訊息。

Step 1: 下載 .jar 檔

NanoHttpd jar 下載網址
https://github.com/NanoHttpd/nanohttpd/releases

Step 2: 將下載的.jar檔案,放置到 (App Name)/lib 資料夾底下

Step 3: build.gradle 中添加 .jar檔的資訊

build.gradle
1
2
3
4
5
6
7
8
android {
...
}

dependencies {
...
compile files('libs/nanohttpd-2.3.1.jar')
}

Step 4: 新增加class,並繼承NanoHTTPD

NanoHttpServer.java
1
2
3
4
5
public class NanoHttpServer extends NanoHTTPD {
public NanoHttpServer(int port) {
super(port);
}
}

Step 5: 建立NanoHttpServer並啟動HttpServer

設定一組port來進行溝通,此例子使用6600 port來監聽socket間的溝通

MainActivity.java
1
2
mHttpServer = new NanoHttpServer(6600);
mHttpServer.start();

Step 6: 接收Client端的訊息

當Client連接上,並傳送訊息時,可由serve(IHTTPSession session) 接收訊息並回傳Response

NanoHttpServer.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@Override
public Response serve(IHTTPSession session) {

String uri = session.getUri();
String method = session.getMethod().name();
String remoteIp = session.getRemoteIpAddress();

NxLog.e(TAG, "uri: " + uri);
NxLog.e(TAG, "method: " + method);
NxLog.e(TAG, "remoteIp: " + remoteIp);

InputStream is = session.getInputStream();
...


String msg = "Send response to client";
return newFixedLengthResponse(msg);
}

不過需要注意的是IHTTPSession的getInputStream,讀完數據流後不會回傳 -1 或者結束符號,必須自己控制何時結束。

我們可取一個buffer size來控制,當讀入的數據長度小於此buffer size則跳出迴圈表示已讀完數據流。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
try {
InputStream is = session.getInputStream();

int buffer_szie = 1024;
byte[] buffer = new byte[buffer_szie];
int length = 0;

do {
length = is.read(buffer);
//...
} while(length >= buffer_szie );
} catch (IOException e) {
e.printStackTrace();
}
作者

Nick Lin

發表於

2019-04-01

更新於

2023-01-18

許可協議


評論