NanoHttpd嵌入式服务器

基于NanoHttpd的Android视频服务器开发

说明
NanoHttpd是个很强大的开源库,仅仅用一个Java类,就实现了一个轻量级的 Web Server,可以非常方便地集成到Android应用中去,让你的App支持 HTTP GET, POST, PUT, HEAD 和 DELETE 请求。

为了演示它的功能,我利用该库搭建了一个简单地Android视频服务器,可以通过PC浏览器远程播放Android手机存储器中的mp4视频文件。

最基本的使用

1)下载该库并添加到你的Android工程中,就可以使用NanoHTTPD类了,该类最重要的三个函数,一个是start(),一个是 stop(),用于启动和停止Web Server,再一个就是serve(),该函数就是收到浏览器的请求后的回调函数,可以在该函数内部给浏览器返回响应的HTTP页面。

下面是一个最简单的对所有请求都返回404错误的示例:

public class VideoServer extends NanoHTTPD {
  public VideoServer(int port) {
    super(port);
  }
  @Override
  public Response serve(IHTTPSession session) {     
    StringBuilder builder = new StringBuilder();
    builder.append("");      
    builder.append("404 -- Sorry, Can't Found "+ session.getUri() + " !");      
    builder.append("\n");
    return new Response(builder.toString());
  }
}

其中,IHTTPSession类提供了一系列的接口,用来判断浏览器的请求内容,包括:GET/PUT类型、请求的URL等等,你可以以此为判断针对不同的请求完成服务或者返回相应的页面。

2)浏览器中播放视频
要想通过浏览器直接播放视频,目前最常见的有两种方式,一种是采用Flash播放器,另一种利用HTML5标签,本文就是采用了HTML5标签实现的。

下面就是Android端收到HTTP请求之后返回的HTML5页面,参考: 《HTML5教程》









浏览器收到该HTML5页面后,会进一步请求标签给出的视频地址,这时Android端就需要通过字节流的形式将本地的视频文件发送给浏览器,代码如下:

public Response responseVideoStream(IHTTPSession session,String videopath) {
  try {
    FileInputStream fis = new FileInputStream(videopath);
    return new NanoHTTPD.Response(Status.OK, "video/mp4", fis);
  } 
  catch (FileNotFoundException e) {     
    e.printStackTrace();
    return new Response("Error");
  } 
}

注意问题

1.签名证书 generating an self signed ssl certificate

keytool -genkey -keyalg RSA -alias selfsigned -keystore keystore.jks -storepass password -validity 360 -keysize 2048 -ext SAN=DNS:localhost,IP:127.0.0.1 -validity 9999

这个应该是https协议需要的东西

  1. 启动方式
    在Android里面服务器的启动使用
//SimpleServer 继承自NanoHTTPD
  SimpleServer simpleServer = new SimpleServer();
        try {
            simpleServer.start();
        } catch (IOException e) {
            e.printStackTrace();
        }

Java里面这么启动

 public static void main(String[] args) {
        ServerRunner.run(SimpleServer.class);
    }

最基本的结构仅仅3个类

NanoHttpd嵌入式服务器_第1张图片
Paste_Image.png

ServerRunner

public class ServerRunner {

    /**
     * logger to log to.
     */
    private static final Logger LOG = Logger.getLogger(ServerRunner.class.getName());

    public static void executeInstance(NanoHTTPD server) {
        try {
            server.start(NanoHTTPD.SOCKET_READ_TIMEOUT, false);
        } catch (IOException ioe) {
            System.err.println("Couldn't start server:\n" + ioe);
            System.exit(-1);
        }

        System.out.println("Server started, Hit Enter to stop.\n");

        try {
            System.in.read();
        } catch (Throwable ignored) {
        }

        server.stop();
        System.out.println("Server stopped.\n");
    }

    public static  void run(Class serverClass) {
        try {
            executeInstance(serverClass.newInstance());
        } catch (Exception e) {
            ServerRunner.LOG.log(Level.SEVERE, "Cound nor create server", e);
        }
    }
}

SimpleServer

package fi.iki.elonen;


import java.util.Map;
import java.util.logging.Logger;

import fi.iki.elonen.NanoHTTPD;

public class SimpleServer extends NanoHTTPD {

    /**
     * logger to log to.
     */
    private static final Logger LOG = Logger.getLogger(SimpleServer.class.getName());

    public static void main(String[] args) {
        ServerRunner.run(SimpleServer.class);
    }

    public SimpleServer() {
        super(8999);
    }

    @Override
    public Response serve(IHTTPSession session) { // 此方法等同于TomCat总控制器,因为没有向Struts2那样映射过,故请求跳转的url需要我们自己处理,此方法会接收所有请求
        Method method = session.getMethod();
        String uri = session.getUri();
        SimpleServer.LOG.info(method + " '" + uri + "' ");

        String msg = "

Hello server

\n"; Map parms = session.getParms(); if (parms.get("username") == null) { msg += "
\n" + "

Your name:

\n" + "
\n"; } else { msg += "

Hello, " + parms.get("username") + "!

"; } msg += "\n"; return newFixedLengthResponse(msg); } }

NanoHttpd(核心类)

太长了不在列举了

由于 每次经过 Response serve会多请求一次
该是浏览器多请求了一个 /favicon.ico
所以这里注意过滤一下

@Override
    public Response serve(IHTTPSession session) { // 此方法等同于TomCat总控制器,因为没有向Struts2那样映射过,故请求跳转的url需要我们自己处理,此方法会接收所有请求
        Method method = session.getMethod();
        String uri = session.getUri();
        SimpleServer.LOG.info(method + " '" + uri + "' ");

        String msg = "

Hello server

\n"; Map parms = session.getParms(); if (parms.get("username") == null) { msg += "
\n" + "

Your name:

\n" + "
\n"; } else { msg += "

Hello, " + parms.get("username") + "!

"; } msg += "\n"; Log.d("wl", msg); if (!uri.contains("favicon.ico")) { callBack.changeText(msg); } return newFixedLengthResponse(msg); }

问题

Post请求的参数接收不到

public MyServer() throws IOException {
        super(PORT);
        File f;
        f = new File("/storage/sdcard0/www");
        if (f.canWrite()) {
            rootDir = "/storage/sdcard0/www";
            System.out.println("rootDir = " + rootDir);
        }
        else {
            f = new File("/storage/sdcard1/www");
            if (f.canWrite()) {
                rootDir = "/storage/sdcard1/www";
                System.out.println("rootDir = " + rootDir);
            }
            else {
                rootDir = "/storage/sdcard0";
                System.out.println("set rootDir default " + rootDir);
            }
        }

        start(NanoHTTPD.SOCKET_READ_TIMEOUT);
    }

文件下载(无文件返回名)

private Response newFixedFileResponse(File file, String mime) throws FileNotFoundException {
        Response res;
        res = newFixedLengthResponse(Response.Status.OK, mime, new FileInputStream(file), (int) file.length());
        res.addHeader("Accept-Ranges", "bytes");
        return res;
    }


文件下载

Server


public class SimpleServer extends NanoHTTPD { 

    public static void main(String[] args) {
        ServerRunner.run(SimpleServer.class);
    }

    public SimpleServer() {
        super(8990);
    }

    @Override
    public Response serve(IHTTPSession session) {
        Method method = session.getMethod();
        String uri = session.getUri();
        String username = session.getQueryParameterString();
        
        System.out.println("method "+method+" uri "+uri+" "+username);
 
   InputStream inputStream;
   Response response = null;
  try {
   inputStream = new FileInputStream(new File("/Users/ruulai/Desktop/some/test.java"));
    response = newChunkedResponse(Status.OK, "application/octet-stream", inputStream);//这代表任意的二进制数据传输。
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  }
  
   response.addHeader("Content-Disposition", "attachment; filename="+"test.java");      
      return response;
       
    }
}

文件上传(稍微麻烦了点)

package fi.iki.elonen;

import android.content.Context;
import android.util.Log;

import com.ruulai.littleserver.IOUtils;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.io.FileUtils;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.InputStream;
import java.util.List;
import java.util.Map;

import fi.iki.elonen.NanoHTTPD.Response.Status;

    //服务端
    public  class TestServer extends NanoHTTPD {
        private Context mContext;
        public TestServer(Context context) {
            super(9999);
            uploader = new NanoFileUpload(new DiskFileItemFactory());
            mContext = context;
        }
           public NanoFileUpload uploader;
           public Response response = newFixedLengthResponse(""); //返回客户端 Response

            public String uri;

            public Method method;

            public Map header;

            public Map parms;

            public Map> files;

            public Map> decodedParamters; // {name=[xiaoming], password=[abcd]}

            public String queryParameterString; //格式如 name=xiaoming&password=abcd

        @Override
        public Response serve(IHTTPSession session) {
            // 测试发现,无论是POST还是GET都会多执行一次 GET /favicon.ico ,且同样拿不到参数
            this.uri = session.getUri();   //访问的请求如 http://192.168.31.118:8192/uploadFile1 ,但是 this.uri 为  /uploadFile1
            this.method = session.getMethod();
            this.header = session.getHeaders();
            this.parms = session.getParms();
            System.out.println("方法是:" + method+" "+uri);
            if (NanoFileUpload.isMultipartContent(session)) {
                try {
                    if ("/uploadFile1".equals(this.uri)) {
//                        session.getHeaders().put("content-length", "AA");
                        files = uploader.parseParameterMap(session);
                        FileItem fileItem = files.get("upfile").get(0);

                        InputStream inputStream = fileItem.getInputStream();
                        BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);

                        FileUtils.copyInputStreamToFile(bufferedInputStream, new File("/sdcard/laji.java"));
                        Log.d("wl", "文件保存成功");


                    }


                } catch (Exception e) {
                    this.response.setStatus(Status.INTERNAL_ERROR);
                    e.printStackTrace();
                }
            }


            this.queryParameterString = session.getQueryParameterString(); //HttpPost post = new HttpPost("http://192.168.31.118:8192/uploadFile1?name=xiaoming&password=abcd");可以获取Post请求参数
            this.decodedParamters = decodeParameters(queryParameterString);

            String usernmae = this.parms.get("username");
            System.out.println(queryParameterString+" "+decodedParamters+" "+usernmae);
//            name=xiaoming&password=abcd {name=[xiaoming], password=[abcd]}

            String html = IOUtils.readFile(mContext);
//            return this.response; // =========》  返回给客户端
            return  newFixedLengthResponse(html) ; // =========》  返回给客户端
        }


        
    }



你可能感兴趣的:(NanoHttpd嵌入式服务器)