NanoHttpd Demo是個好東西

NanoHttpd Demo是個好東西

前幾天,在做一個視頻BT項目的時候,看各種博文之類的,突然就看到提出了一個NanoHttpd視頻服務器的博文。於是就跟進去看了一下,發現,裏面就一個鏈接。
GitHub地址:https://github.com/NanoHttpd/nanohttpd
然後就沒了。。。
本來像這種標題黨,我已經舉報他。可是,我又很想知道,所以我就跟進去看了一下,NanoHttpd,嗯,一個Java文件的項目,嗯。
然後研究了一下源碼,發現,從所未有的爽,的確,給個鏈接就夠了。

這裏貼一個簡單的Demo,來自NanoHttpd。

package fi.iki.elonen;

/*
 * #%L
 * NanoHttpd-Samples
 * %%
 * Copyright (C) 2012 - 2015 nanohttpd
 * %%
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 * 
 * 1. Redistributions of source code must retain the above copyright notice, this
 *    list of conditions and the following disclaimer.
 * 
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 * 
 * 3. Neither the name of the nanohttpd nor the names of its contributors
 *    may be used to endorse or promote products derived from this software without
 *    specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
 * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 * OF THE POSSIBILITY OF SUCH DAMAGE.
 * #L%
 */

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

import fi.iki.elonen.util.ServerRunner;

/**
 * An example of subclassing NanoHTTPD to make a custom HTTP server.
 */
public class HelloServer extends NanoHTTPD {

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

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

    public HelloServer() {
        super(8080);
    }

    @Override
    public Response serve(IHTTPSession session) {
        Method method = session.getMethod();
        String uri = session.getUri();
        HelloServer.LOG.info(method + " '" + uri + "' ");

        String msg = "<html><body><h1>Hello server</h1>\n";
        Map<String, String> parms = session.getParms();
        if (parms.get("username") == null) {
            msg += "<form action='?' method='get'>\n" + "  <p>Your name: <input type='text' name='username'></p>\n" + "</form>\n";
        } else {
            msg += "<p>Hello, " + parms.get("username") + "!</p>";
        }

        msg += "</body></html>\n";

        return newFixedLengthResponse(msg);
    }
}

只要你導包,然後運行上面的東西就可以用瀏覽器訪問8080端口,就能看到輸出了,簡單明瞭。
因此我就對他進行了一些改動,變成一個視頻網站的項目,代碼如下。

package com.chen.video.resource;


import fi.iki.elonen.NanoHTTPD;

import java.io.FileInputStream;
import java.io.FileNotFoundException;

import static fi.iki.elonen.NanoHTTPD.newChunkedResponse;

/**
 * Created by CHEN on 2016/8/14.
 */
public class VideoResource {

    public static NanoHTTPD.Response getVideo(String videoURI) {
        try {
            FileInputStream fis = new FileInputStream(videoURI);
            return newChunkedResponse(NanoHTTPD.Response.Status.OK, "movie.mp4", fis);
        }
        catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        }
    }

}
package com.chen.video;

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

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

/**
 * Created by CHEN on 2016/8/14.
 */
public class VideoServer extends NanoHTTPD{
    public static final int DEFAULT_SERVER_PORT = 8080;
    public static final String TAG = VideoServer.class.getSimpleName();
    public String filePath= "movie.mp4";
    private static final String REQUEST_ROOT = "/";

    private String mVideoFilePath;
    private int mVideoWidth  = 0;
    private int mVideoHeight = 0;

    private static final int VIDEO_WIDTH= 320;
    private static final int VIDEO_HEIGHT = 240;


    public VideoServer() {
        super(DEFAULT_SERVER_PORT);
        mVideoFilePath = filePath;
        mVideoWidth  = VIDEO_WIDTH;
        mVideoHeight = VIDEO_HEIGHT;
    }

    @Override
    public Response serve(IHTTPSession session) {
        if(REQUEST_ROOT.equals(session.getUri())) {
            return responseRootPage(session);
        }
        else if("/movie.mp4".equals(session.getUri())) {
            return responseVideoStream(session);
        }
        return response404(session,session.getUri());
    }

    public Response responseRootPage(IHTTPSession session) {
        String rootURL=this.getClass().getResource("/").getPath();
        File file = new File(rootURL+"/com/chen/video/"+mVideoFilePath);
       /* if(!file.exists()) {
            return response404(session,mVideoFilePath);
        }*/
        StringBuilder builder = new StringBuilder();
        builder.append("<!DOCTYPE html><html><body>");
        builder.append("<video ");
        builder.append("width="+getQuotaStr(String.valueOf(mVideoWidth))+" ");
        builder.append("height="+getQuotaStr(String.valueOf(mVideoHeight))+" ");
        builder.append("controls>");
        builder.append("<source src="+getQuotaStr("/movie.mp4")+" ");
        builder.append("type="+getQuotaStr("video/mp4")+">");
        builder.append("Your browser doestn't support HTML5");
        builder.append("</video>");
        builder.append("</body></html>\n");
        return newFixedLengthResponse(builder.toString());
    }

    public Response responseVideoStream(IHTTPSession session) {
        try {
            FileInputStream fis = new FileInputStream(this.getClass().getResource("/").getPath()+"/com/chen/video/"+mVideoFilePath);
            return newChunkedResponse(Status.OK, "movie.mp4", fis);
        }

        catch (FileNotFoundException e) {
            e.printStackTrace();
            return response404(session,mVideoFilePath);
        }
    }

    public Response response404(IHTTPSession session,String url) {
        StringBuilder builder = new StringBuilder();
        builder.append("<!DOCTYPE html><html><body>");
        builder.append("Sorry, Can't Found "+url + " !");
        builder.append("</body></html>\n");
        return newFixedLengthResponse(builder.toString());
    }


    protected String getQuotaStr(String text) {
        return "\"" + text + "\"";
    }

    public static void main(String[] args) {

        ServerRunner.run(VideoServer.class);
    }
}
package com.chen.video;

import com.chen.video.resource.VideoResource;
import fi.iki.elonen.NanoHTTPD;
import fi.iki.elonen.util.ServerRunner;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import static com.chen.video.resource.VideoResource.getVideo;
import static jdk.nashorn.internal.objects.NativeString.substring;


/**
 * Created by CHEN on 2016/8/14.
 */
public class MyVideoServer extends NanoHTTPD {


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


    public MyVideoServer() {
        super(8088);
    }

    @Override
    public Response serve(IHTTPSession session) {
        //在這裏做一些跳轉的控制
      /*註釋說明:這裏感覺太耗資源了,沒必要,所以改成以下形式
       if(session.getUri().contains("page")) {//說明是頁面

        } else if(session.getUri().contains("resource")) {

        }*/
        //TODO 規定一級路徑爲類,二級路徑爲方法
        //TODO 規定資源都是一級路徑
        //現在暫時簡單實現,畢竟是教學
        String uri = session.getUri();
        String[] uriSplit = uri.split("/");
        Response response = null;
        switch (uriSplit[1].charAt(0)){
            case 'p': {//page
                String classURI = uriSplit[2].substring(0, 1).toUpperCase() + uriSplit[2].substring(1) + "Controller";
                try {
                    Class clazz = Class.forName("com.chen.video.controller."+classURI);
                    java.lang.reflect.Method method = clazz.getMethod("getVideoPage");
                    response = (Response) method.invoke(null);
                } catch (Exception e) {
                    //TODO 其實拋出了很多的異常 但是爲了代碼不要被異常包圍,先統一處理
                    e.printStackTrace();
                }
            }
            break;
            case 'r': {//resource
                //本來應該有一個資源分類的 比如說是音頻還是書籍 但是這裏也統一處理了 默認是音頻
                String resourceURI=uriSplit[2];
                response= VideoResource.getVideo(this.getClass().getResource("/").getPath()+"com/chen/video/"+resourceURI);
            }
            break;
            default: {}break;
        }

        //異常處理
        if(null!=response) {
            return response;
        } else {
            //TODO 處理
            return null;
        }
    }
}

請注意一點,NanoHttpd是一個BIO項目。

源碼解讀

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章