设为首页 加入收藏

TOP

Java实现一个简单的Web服务器(二)
2015-07-16 12:57:48 来源: 作者: 【 】 浏览:120
Tags:Java 实现 一个 简单 Web 服务器
he directory where our html and other files reside.
? * For this package,WEB_ROOT is the "webroot" directory under the
? * working directory.
? * the working directory is the location in the file system
? * from where the java command was invoke.
? */
?public static final String WEB_ROOT=System.getProperty("user.dir")+File.separator+"webroot";
?
?private static final String SHUTDOWN_COMMAND="/SHUTDOWN";
?
?private boolean shutdown=false;
?
?public static void main(String[] args) {
? HttpServer server=new HttpServer();
? server.await();
?}
?
?public void await(){
? ServerSocket serverSocket=null;
? int port=8080;
? try {
? ?serverSocket=new ServerSocket(port,1,InetAddress.getByName("127.0.0.1"));
? } catch (Exception e) {
? ?e.printStackTrace();
? ?System.exit(0);
? }
? while(!shutdown){
? ?Socket socket=null;
? ?InputStream input=null;
? ?OutputStream output=null;
? ?try {
? ? socket=serverSocket.accept();
? ? input=socket.getInputStream();
? ? output=socket.getOutputStream();
? ? //create Request object and parse
? ? Request request=new Request(input);
? ? request.parse();
? ?
? ? //create Response object
? ? Response response=new Response(output);
? ? response.setRequest(request);
? ? response.sendStaticResource();
? ?} catch (Exception e) {
? ? e.printStackTrace();
? ? continue;
? ?}
? }
?}
}


这个类表示一个Web服务器,这个Web服务器可以处理对指定目录的静态资源的请求,该目录包括由公有静态变量final WEB_ROOT指明的目录及其所有子目录。


现在在webroot中创建一个html页面,命名为index.html,源码如下:






Insert title here


?

Hello World!




现在启动该WEB服务器,并请求index.html静态页面。


Java实现一个简单的Web服务器


所对应的控制台的输出:


Java实现一个简单的Web服务器


如此,一个简单的http服务器便完成了。


首页 上一页 1 2 下一页 尾页 2/2/2
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇Java JNI开发实践记录 下一篇Java源码实现观察者模式实例

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: