Posted on 2009-06-19 16:36
沙漠中的鱼 阅读(1428)
评论(0) 编辑 收藏 所属分类:
系统架构 、
Java 、
Java基础
HttpServer.java
package htmlbrowser;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Properties;
import java.io.IOException;
import java.util.Enumeration;
import java.net.ServerSocket;
import java.net.Socket;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
public class HttpServer
{
private int iPort = 8080; //default port
public static String Basic_Root=System.getProperty("user.dir");
public static String WEB_ROOT = System.getProperty("user.dir") +
File.separator + "webroot";
public static int count=0;
public HttpServer()
{
System.out.println("欢迎使用Erik‘s 快速Web服务器,本服务器只支持静态网页。");
System.out.println("检查配置文件及网页文件夹");
getConfig();
start();
}
public static void main(String[] args)
{
HttpServer httpserver = new HttpServer();
}
private void getConfig()
{
File fileCon=new File(Basic_Root,"config.ini");
File fileDir=new File(WEB_ROOT);
File fileWeb=new File(WEB_ROOT,"index.htm");
if(!fileCon.exists())
{
System.out.println("配置文件Config.ini损坏,重建中");
reBuildConfig(fileCon);
}
if (!fileDir.exists())
{
System.out.println("网页存放文件夹不存在,重建中");
fileDir.mkdir();
System.out.print("完成!请在");
System.out.println(WEB_ROOT+"中放置网页文件");
System.out.println("Web服务器将重新初始化");
getConfig();
}
if (!fileWeb.exists())
{
reBuildWeb(fileWeb);
}
Properties pps = new Properties();
try
{
pps.load(new FileInputStream("config.ini"));
Enumeration enumer = pps.propertyNames();
String strKey = (String) enumer.nextElement();
String strValue = pps.getProperty(strKey);
if (strValue.equals("") != true)
{
WEB_ROOT = strValue;
}
System.out.println("网页文件的存放路径为: "+WEB_ROOT);
strKey = (String) enumer.nextElement();
strValue = pps.getProperty(strKey);
if (strValue.equals("") != true)
{
iPort = Integer.parseInt(strValue);
}
System.out.println("Web服务器访问端口为:"+iPort);
System.out.println("您可以修改Config.ini文件重新设定以上配置");
System.out.println("启动检查完成,服务器初始化中");
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
public void start()
{
System.out.println("Web 服务器启动中");
ServerSocket serverSocket;
try
{
serverSocket = new ServerSocket(iPort);
System.out.println("Web 启动完成!");
System.out.println("您现在可以在浏览器中访问http://localhost:8080/,以测试服务器是否运行");
while (true)
{
Socket socket = null;
InputStream input = null;
OutputStream output = null;
System.out.println("等待连接");
socket = serverSocket.accept();
System.out.println(socket.getInetAddress().toString()+"请求连接");
input=socket.getInputStream();
output=socket.getOutputStream();
System.out.println("服务器开始处理第"+(++count)+"次连接");
//开始处理并分析请求信息
Request request=new Request(input);
request.parse();
//开始发送请求资源
Response response=new Response(output);
response.setRequest(request);
response.sendStaticResource();
//关系连接
socket.close();
System.out.println("连接已关闭!");
}
}
catch(Exception ex)
{
ex.printStackTrace();
System.out.println("3");
//continue;
}
}
private void reBuildConfig(File file)
{
try
{
file.createNewFile();
FileOutputStream fos=new FileOutputStream(file);
PrintStream sp=new PrintStream(fos);
sp.println("WEB_ROOT=");
sp.println("PORT=");
sp.close();
System.out.println("配置文件Config.ini创建成功,您可以修改WEB_ROOT的值改变网页文件的存放路径,修改PORT的值改变访问端口!");
}
catch (IOException ex)
{
ex.printStackTrace();
System.out.println("重建配置文件Config.ini失败");
System.out.println("服务器将使用默认配置");
}
}
private void reBuildWeb(File file)
{
try
{
file.createNewFile();
FileOutputStream fos=new FileOutputStream(file);
PrintStream sp=new PrintStream(fos);
sp.println("<html>");
sp.println("<head>");
sp.println("<title>Erik'简单Web服务器</title>");
sp.println("</head>");
sp.println("<body>");
sp.println("<div align="+"center"+">服务器已经成功运行 </div>");
sp.println("</body>");
sp.println("</html>");
sp.close();
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
}
Request.java
package htmlbrowser;
import java.io.InputStream;
public class Request
{
public Request()
{
}
private InputStream input;
private String uri;
public Request(InputStream input)
{
this.input = input;
}
public void parse()//取得请求信息
{
StringBuffer request = new StringBuffer(2048);
int i;
byte[] buffer = new byte[2048];
try
{
i = input.read(buffer);
}
catch (Exception ex)
{
ex.printStackTrace();
i = -1;
}
for (int j = 0; j < i; j++)
{
request.append((char) buffer[j]);
}
System.out.println(request.toString());
uri = parseUri(request.toString());
System.out.println("用户请求:"+this.getUri());
}
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()
{
if (uri.compareTo("/")==0)
{
uri="/index.htm";
}
if (uri.indexOf(".")==-1)
{
uri+=".htm";
}
return uri;
}
}
Response.java
package htmlbrowser;
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())
{
System.out.println("开始发送用户请求资源");
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);
}
System.out.println("发送完毕!");
}
else
{
System.out.println("用户请求的资源不存在");
String errorMessage = "HTTP/1.1 404 File Not Found\r\n" +
"Content-Type:text/html\r\n" +
"\r\n" +
"<hl>File Not Found</hl>";
output.write(errorMessage.getBytes());
}
}
catch (Exception ex)
{
ex.printStackTrace();
System.out.println("获取请求资源错误,请检查本地资源设置!");
System.exit(1);
}
if (fis != null)
{
fis.close();
}
}
}
转载:http://www.javaresearch.org/code/thread.jsp?column=721&thread=35194