Posted on 2009-06-19 16:36
沙漠中的魚 閱讀(1452)
評論(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