Set up HttpServer - NanoHttpd

NanoHttp is a light-weight HTTP server designed for embedding system, released under a BSD licence.

Step 1: Download .jar

NanoHttpd Github

Step 2: Import .jar

Unzip file and copy .jar file to your project/libs folder.

Step 3: Add info in build.gradle

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

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

Step 4: Create custom class

Create a custom class and extends NanoHTTPD.

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

Step 5: Create NanoHttpServer

Created NanoHttpServer and start http server and set up a custom port to communicate with client.

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

Step 6: Receive message from client

When client is connected, we can receive the message and return response to client.

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);
}

It should be noted that IHTTPSession.getInputStream will never return -1 as end of stream.

But we could use a buffer to control loop. When the length of reading stream less than buffer size, than we break this loop.

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();
}
Author

Nick Lin

Posted on

2019-04-01

Updated on

2023-01-18

Licensed under


Comments