一个JAVA的WEB服务器事例
其实编写一个入门级别的JAVA的WEB服务器,很简单,用SOCKET类即可实现。相关内容可以参考:http://www.cnblogs.com/liqiu/p/3253022.html
一、首先创建一个目录,目录内结构如下:
@~/study/webserver $ tree
.
├── src
│ └── com
│ └── taobao
│ ├── HttpServer.java
│ ├── Request.java
│ └── Response.java
└── webroot
└── index.html
二、创建文件:
index.html
<html>
<head>
<title>Hello</title>
</head>
<body>
<br>
World
</body>
</html>
pyrmont目录的三个java文件,分别是:
HttpServer.java
package com.taobao; import java.net.Socket;
import java.net.ServerSocket;
import java.net.InetAddress;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
import java.io.File; public class HttpServer { public static final String WEB_ROOT = System.getProperty("user.dir") + File.separator + "webroot"; // shutdown command
private static final String SHUTDOWN_COMMAND = "/SHUTDOWN"; // the shutdown command received
private boolean shutdown = false; public static void main(String[] args) {
HttpServer server = new HttpServer();
server.await();
} public void await() {
ServerSocket serverSocket = null;
int port = 8389;
try {
serverSocket = new ServerSocket(port, 1, InetAddress.getByName("127.0.0.1"));
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
} // Loop waiting for a request
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(); // Close the socket
socket.close(); // check if the previous URI is a shutdown command
shutdown = request.getUri().equals(SHUTDOWN_COMMAND);
} catch (Exception e) {
e.printStackTrace();
continue;
}
}
}
}
Request.java
package com.taobao; import java.io.InputStream;
import java.io.IOException; public class Request { private InputStream input;
private String uri; public Request(InputStream input) {
this.input = input;
} public void parse() {
// Read a set of characters from the socket
StringBuffer request = new StringBuffer(2048);
int i;
byte[] buffer = new byte[2048];
try {
i = input.read(buffer);
} catch (IOException e) {
e.printStackTrace();
i = -1;
}
for (int j = 0; j < i; j++) {
request.append((char) buffer[j]);
}
System.out.print("************************");
System.out.print(request.toString());
System.out.print("------------------------");
uri = parseUri(request.toString());
} private String parseUri(String requestString) {
int index1, index2;
index1 = requestString.indexOf(' ');
if (index1 != -1) {
index2 = requestString.indexOf(' ', index1 + 1);
if (index2 > index1)
return requestString.substring(index1 + 1, index2);
}
return null;
} public String getUri() {
return uri;
} }
Response.java
package com.taobao; import java.io.OutputStream;
import java.io.IOException;
import java.io.FileInputStream;
import java.io.File; public class Response { private static final int BUFFER_SIZE = 1024;
Request request;
OutputStream output; public Response(OutputStream output) {
this.output = output;
} public void setRequest(Request request) {
this.request = request;
} public void sendStaticResource() throws IOException {
byte[] bytes = new byte[BUFFER_SIZE];
FileInputStream fis = null;
try {
File file = new File(HttpServer.WEB_ROOT, request.getUri());
if (file.exists()) {
fis = new FileInputStream(file);
int ch = fis.read(bytes, 0, BUFFER_SIZE);
while (ch != -1) {
output.write(bytes, 0, ch);
ch = fis.read(bytes, 0, BUFFER_SIZE);
}
} else {
// file not found
String errorMessage = "HTTP/1.1 404 File Not Found\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 23\r\n" + "\r\n"
+ "<h1>File Not Found</h1>";
output.write(errorMessage.getBytes());
}
} catch (Exception e) {
// thrown if cannot instantiate a File object
System.out.println(e.toString());
} finally {
if (fis != null)
fis.close();
}
}
}
三、在原始目录编译文件
javac -d . ./src/com/taobao/*.java
@~/study/webserver $ tree
执行成功之后的目录如下:
.
├── com
│ └── taobao
│ ├── HttpServer.class
│ ├── Request.class
│ └── Response.class
├── src
│ └── com
│ └── taobao
│ ├── HttpServer.java
│ ├── Request.java
│ └── Response.java
└── webroot
└── index.html directories, files
四、执行内容
java com.taobao.HttpServer
五、查看结果
在浏览器输入:http://localhost:8389/index.html
查看的内容是:world
一个JAVA的WEB服务器事例的更多相关文章
- 使用java基础实现一个简陋的web服务器软件
使用java基础实现一个简陋的web服务器软件 1.写在前面 大学已经过了一年半了,从接触各种web服务器软件已经有一年多了,从大一上最开始折腾Windows电脑自带的IIS开始,上手了自己的第一个静 ...
- JAVA编写WEB服务器
一.超文本传输协议 1.1 HTTP请求 1.2 HTTP应答 二.Socket类 三.ServerSocket类 四.Web服务器实例 4.1 HttpServer类 4.2 Requ ...
- (一)一个简单的Web服务器
万丈高楼平地起,首先我们必须了解 超文本传输协议(HTTP) 以后才能够比较清晰的明白web服务器是怎么回事. 1. 浅析Http协议 HTTP是一种协议,允许web服务器和浏览器通过互联网进行来发送 ...
- Tomcat剖析(一):一个简单的Web服务器
Tomcat剖析(一):一个简单的Web服务器 1. Tomcat剖析(一):一个简单的Web服务器 2. Tomcat剖析(二):一个简单的Servlet服务器 3. Tomcat剖析(三):连接器 ...
- 实战WEB 服务器(JAVA编写WEB服务器)
实战WEB 服务器(JAVA编写WEB服务器) 标签: web服务服务器javawebsockethttp服务器 2010-04-21 17:09 11631人阅读 评论(24) 收藏 举报 分类: ...
- 自己模拟的一个简单的web服务器
首先我为大家推荐一本书:How Tomcat Works.这本书讲的很详细的,虽然实际开发中我们并不会自己去写一个tomcat,但是对于了解Tomcat是如何工作的还是很有必要的. Servlet容器 ...
- (转载)关于java多线程web服务器 以及相关资料转载
1.自己实现的简单的java多线程web服务器: https://blog.csdn.net/chongshangyunxiao321/article/details/51095149 自己实现一个简 ...
- 《深度解析Tomcat》 第一章 一个简单的Web服务器
本章介绍Java Web服务器是如何运行的.从中可以知道Tomcat是如何工作的. 基于Java的Web服务器会使用java.net.Socket类和java.net.ServerSocket类这两个 ...
- 自己动手模拟开发一个简单的Web服务器
开篇:每当我们将开发好的ASP.NET网站部署到IIS服务器中,在浏览器正常浏览页面时,可曾想过Web服务器是怎么工作的,其原理是什么?“纸上得来终觉浅,绝知此事要躬行”,于是我们自己模拟一个简单的W ...
随机推荐
- C#编程(三十四)----------数组作为参数
原文链接: http://blog.csdn.net/shanyongxu/article/details/46765267 数组作为参数 数组可以作为参数传递给方法,也可以从方法中返回.要返回一个数 ...
- MQ:Introducing Advanced Messaging
原文地址:http://www.yourenterprisearchitect.com/2011/11/introducing-advanced-messaging.html. Introducing ...
- Git每次进入都需要输入用户名和密码的问题解决
解决方法: 在项目目录下输入以下命令: git config --global credential.helper store 使用git pull 的时候回提示再输下用户名和密码就行了.
- bat与jscript开发工具时遇到的一些问题
之前使得bat调用luac进行编译时,会弹出一个"黑色的界面",闪烁一下,感觉不太好.而脚本vbs或者jscript调用bat是可以利用Run方法,将其第二个参数设置为0便可以隐藏 ...
- 用SAX和PULL进行XML文件的解析与生成
XML解析有传统的dom方法还有Jsoup,SAX,PULL等,这里讲的是比较省内存的SAX和PULL方法.Android中极力推荐用PULL的方式来解析,我个人觉得pull确实比较简单,但其内部的逻 ...
- Dockerfile 指令汇总及解析
原文地址:http://www.maoyupeng.com/dockerfile-command-introduction.html 什么是Dockerfile Dockerfile是由一系列 ...
- 解决tensorflow在训练的时候权重是nan问题
搭建普通的卷积CNN网络. nan表示的是无穷或者是非数值,比如说你在tensorflow中使用一个数除以0,那么得到的结果就是nan. 在一个matrix中,如果其中的值都为nan很有可能是因为采用 ...
- pssh,pdsh,mussh,cssh,dsh运维工具介绍
pssh 1 安装:#wget http://peak.telecommunity.com/dist/ez_setup.pypython ez_setup.py#wget http://paralle ...
- iOS:麦克风权限检测和获取
一.检测 该方法是用来判断麦克风是否进行过授权,如果授权过就直接进行需要的功能操作:如果没有进行授权,那么就要获取授权. AVAuthorizationStatus authStatus = [AVC ...
- Linq的延迟加载问题
什么是延迟加载:所谓延迟加载就是当在真正需要数据的时候,才真正执行数据加载操作.可以简单理解为,只有在使用的时候,才会发出sql语句进行查询,数据是分N次读取. 什么是立即加载:所谓立即加载既是所有的 ...