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 = "Hello server
\n";
Map<String, String> parms = session.getParms();
if (parms.get("username") == null) {
msg += " + " Your name:
\n" + "\n";
} else {
msg += "Hello, "
+ parms.get("username") + "!";
}
msg += "\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("");
builder.append("");
builder.append("\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("");
builder.append("Sorry, Can't Found "+url + " !");
builder.append("\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项目。
源码解读