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项目。

源码解读

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
NanoHTTPD是一个免费、轻量级的(只有一个Java文件) HTTP服务器,可以很好地嵌入到Java程序中。支持 GET, POST, PUT, HEAD 和 DELETE 请求,支持文件上传,占用内存很小。可轻松定制临时文件使用和线程模型。NanoHTTPD for JDK 1.1https://github.com/NanoHttpd/nanohttpd/tree/nanohttpd-for-java1.1示例代码:package fi.iki.elonen.debug;   import fi.iki.elonen.NanoHTTPD; import fi.iki.elonen.ServerRunner;   import java.util.HashMap; import java.util.List; import java.util.Map;   public class DebugServer extends NanoHTTPD {     public DebugServer() {         super(8080);     }       public static void main(String[] args) {         ServerRunner.run(DebugServer.class);     }       @Override public Response serve(IHTTPSession session) {         Map<String, List<String>> decodedQueryParameters =             decodeParameters(session.getQueryParameterString());           StringBuilder sb = new StringBuilder();         sb.append("<html>");         sb.append("<head><title>Debug Server</title></head>");         sb.append("<body>");         sb.append("<h1>Debug Server</h1>");           sb.append("<p><blockquote><b>URI</b> = ").append(             String.valueOf(session.getUri())).append("<br />");           sb.append("<b>Method</b> = ").append(             String.valueOf(session.getMethod())).append("</blockquote></p>");           sb.append("<h3>Headers</h3><p><blockquote>").             append(toString(session.getHeaders())).append("</blockquote></p>");           sb.append("<h3>Parms</h3><p><blockquote>").             append(toString(session.getParms())).append("</blockquote></p>");           sb.append("<h3>Parms (multi values?)</h3><p><blockquote>").             append(toString(decodedQueryParameters)).append("</blockquote></p>");           try {             Map<String, String> files = new HashMap<String, String>();             session.parseBody(files);             sb.append("<h3>Files</h3><p><blockquote>").                 append(toString(files)).append("</blockquote></p>");         } catch (Exception e) {             e.printStackTrace();         }           sb.append("</body>");         sb.append("</html>");         return new Response(sb.toString());     }       private String toString(Map<String, ? extends Object> map) {         if (map.size() == 0) {             return "";         }         return unsortedList(map);     }       private String unsortedList(Map<String, ? extends Object> map) {         StringBuilder sb = new StringBuilder();         sb.append("<ul>");         for (Map.Entry entry : map.entrySet()) {             listItem(sb, entry);         }         sb.append("</ul>");         return sb.toString();     }       private void listItem(StringBuilder sb, Map.Entry entry) {         sb.append("<li><code><b>").append(entry.getKey()).             append("</b> = ").append(entry.getValue()).append("</code></li>");     } } 标签:NanoHTTPD

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值