/*
演示一个简单WEB服务器,网页的文字图形音乐都能展示的目标基本实现。
未来目标:1、完善路由函数
2、实现GET POST数据上传
3、数据能实现sqlite3存储
*/
// 导入调试库、线程库、simpleHttpServer库、网卡库
import console;
import process;
import wsock.tcp.simpleHttpServer;
import inet.adapter;
// 确定本机IP 用于服务器绑定IP
for adptInfo in inet.adapter.each() {
if ( string.match(adptInfo.description ,"本地连接")){
webIp = adptInfo.currentIpAddress;
break ;
}elseif( string.match(adptInfo.description ,"无线网络连接") ){
webIp = adptInfo.currentIpAddress;
break ;
}
}
//启动 ip为webIp,端口为80的服务器线程。
var srvHttp = wsock.tcp.simpleHttpServer( webIp ,80);
//cmd模式显示 url连接 ,WIN系统调出默认浏览器测试网页情况效果。
console.log(srvHttp.getUrl());
process.execute(srvHttp.getUrl());
//服务器响应后各种处理步骤,放在匿名函数function(response,request)内。
srvHttp.run(
function(response,request){
//导入输入输出库、字符串操作库、url解析库
import io;
import string;
import inet.url;
import console;
/*
设计路由函数:
参数:url
返回:目标路径、目标文件类型、错误标记、错误页面
*/
var UrlRouter =function(url){
var errorFlag = false;
//计算目标路径
var sfile = url;
if( sfile == "/" || sfile ="/main.aardio"){
sfile = "d:\web\index.html";
}else{
sfile = "d:\web" + string.replace(sfile,"/","");
}
//计算目标文件类型
var ctType ="";
if(string.match(sfile,".")){}else{sfile = sfile+".*"};
ext = string.split( sfile,'.')[2];
select(ext) {
case "html" { ctType ="text/html"; }
case "htm" { ctType ="text/html"; }
case "xml" { ctType ="text/xml"; }
case "js" { ctType ="application/x-javascript";}
case "css" { ctType ="text/css";}
case "txt" { ctType ="text/plain";}
case "jpg" { ctType ="image/jpeg";}
case "png" { ctType ="image/image/png";}
case "gif" { ctType ="image/image/gif";}
case "ico" { ctType ="image/image/x-icon";}
case "bmp" { ctType = "application/x-bmp";}
case "*" { ctType ="application/octet-stream";}
else {
ctType ="application/octet-stream";
}
}
//目标文件不存在404处理
var fullpath = io.exist( sfile );
if( ! fullpath ){
var page404 = /*
404错误 - HTTP made by Aardio"don't busy on trying, maybe you just took a wrong way of opening."
-- kindly tip from 404
*/
errorFlag = true;
errhtml = page404;
}
return sfile, ctType, errorFlag, errhtml;
};
/*
服务器响应后各种处理步骤:
第一步,通过获取到的 请求响应request对象的url属性,分解出url中的path。
第二步,将path传去路由函数,为了获取 目标路径、目标文件类型、错误标记、错误页面 等结果。
第三步,依据路由函数返回的结果。
回复对象的contentType属性设置为路由函数返回的目标文件类型。
回复对象的传送数据:错真就传错误页面,错假就传目标文件的二进制数据 。
回复对象的其他属性按simpleHttpServer内置默认的。
*/
var url = request.url ;
var urlArray = inet.url.split( url );
var urlPath = urlArray.path;
console.log(urlPath);
var sfile, ctType, err, errdate = UrlRouter(urlPath);
if(err){
response.writeBuffer( errdate ,string.len(errdate));
}else {
var file = io.open(sfile,"rb");
while(
var buf;
buf,readSize = file.read(1024);
buf
){
response.contentType = ctType;
response.writeBuffer(buf,readSize) ;
}
file.close();
}
response.close();
})