先把服务器搭起来
依赖库
首先,依赖下我们搭建Server需要用到的库:
compile ‘com.koushikdutta.async:androidasync:2.+’
1
2
编写简易html
然后我们在assets下编写一个html文件用于浏览器访问,index.html
最简单的即可:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
连通了...
</body>
</html>
服务,监听端口
public class MainActivity extends AppCompatActivity {
private AsyncHttpServer server = new AsyncHttpServer();
private AsyncServer mAsyncServer = new AsyncServer();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
server.get("/", new HttpServerRequestCallback() {
@Override
public void onRequest(AsyncHttpServerRequest request, AsyncHttpServerResponse response) {
try {
response.send(getIndexContent());
} catch (IOException e) {
e.printStackTrace();
response.code(500).end();
}
}
});
server.listen(mAsyncServer, 54321);
}
@Override
protected void onDestroy() {
super.onDestroy();
if (server != null) {
server.stop();
}
if (mAsyncServer != null) {
mAsyncServer.stop();
}
}
private String getIndexContent() throws IOException {
BufferedInputStream bInputStream = null;
try {
bInputStream = new BufferedInputStream(getAssets().open("index.html"));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int len = 0;
byte[] tmp = new byte[10240];
while ((len = bInputStream.read(tmp)) > 0) {
baos.write(tmp, 0, len);
}
return new String(baos.toByteArray(), "utf-8");
} catch (IOException e) {
e.printStackTrace();
throw e;
} finally {
if (bInputStream != null) {
try {
bInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
可以看到很简单,创建AsyncHttpServer对象,我们在onCreate中调用get,对外设置一个get型的url监听,监听的url是/即根目录。
然后调用listen,传入端口号54321,开启对该端口的监听。
onDestroy的时候停止服务器。
当捕获到对”/”的访问时,读取assets下的index.html返回给浏览器。
记得添加网络权限。
好了,运行demo,测试一下。
输入地址,你的手机的IP:端口号。
注意电脑和手机在同一个网段!
完善Demo
接下来,我们将手机上的mp4返回让其在浏览器上显示。
很简单,既然我们可以监听/,返回一个index.html,我们就能监听另一个url,返回文件目录。
server.get("/files", new HttpServerRequestCallback() {
@Override
public void onRequest(AsyncHttpServerRequest request, AsyncHttpServerResponse response) {
JSONArray array = new JSONArray();
File dir = new File(Environment.getExternalStorageDirectory().getPath());
String[] fileNames = dir.list();
if (fileNames != null) {
for (String fileName : fileNames) {
File file = new File(dir, fileName);
if (file.exists() && file.isFile() && file.getName().endsWith(".mp4")) {
try {
JSONObject jsonObject = new JSONObject();
jsonObject.put("name", fileName);
jsonObject.put("path", file.getAbsolutePath());
array.put(jsonObject);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
response.send(array.toString());
}
});
我们监听/files这个Url,然后返回Sdcard根目录的视频文件,拼接成JSON返回。
这里如果你重新启动,在浏览器上输入:
但是我们需要在刚才的html上显示,所以这个请求应该是刚才的Html页面发起:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="jquery-1.7.2.min.js" type="text/javascript"></script>
<title>文档的标题</title>
<script type="text/javascript">
$(function() {
var now = new Date();
var url = 'files' + '?' + now.getTime();
// 请求JSON数据
$.getJSON(url, function(data) {
// 编辑JSON数组
for (var i = 0; i < data.length; i++) {
// 为每个对象生成一个li标签,添加到页面的ul中
var $li = $('<li>' + data[i].name + '</li>');
$li.attr("path", data[i].path);
$("#filelist").append($li);
}
});
});
</script>
</head>
<body>
<ul id="filelist" style="float:left;"></ul>
</body>
</html>
可能很多朋友没了解过js,不过应该能看明白,$.getJSON获取返回的JSON数组,然后遍历为每个Json对象生成一个li标签,添加到页面上。
这里用了jquery,对于js的也需要也请求处理,这里省略了,很简单,看源码即可。