import java.io.* ;
import java.net.* ;
import java.util.* ;
public final class WebServer {
public static void main(String argv[]) throws Exception {
// 得到端口号
int port = 7890;
ServerSocket socket = new ServerSocket(port);
// 执行无限循环的HTTP请求
while (true) {
// 监听TCP请求
Socket connection = socket.accept();
// 构建对象处理HTTP请求
HttpRequest request = new HttpRequest(connection);
// 创建新的线程处理请求
Thread thread = new Thread(request);
thread.start();
}
}
}
final class HttpRequest implements Runnable {
final static String CRLF = "\r\n";
Socket socket;
// 构造函数
public HttpRequest(Socket socket) throws Exception {
this.socket = socket;
}
// 实现run()
public void run() {
try {
processRequest();
} catch (Exception e) {
System.out.println(e);
}
}
private void processRequest() throws Exception {
// 完成对socket的输入输出流的引用
InputStream is = socket.getInputStream();
DataOutputStream os = new DataOutputStream(socket.getOutputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(is));
//获得HTTP请求的信息
String requestLine = br.readLine();
//获得请求行的文件名
StringTokenizer tokens = new StringTokenizer(requestLine);
tokens.nextToken();
//越过"GET"
String fileName = tokens.nextToken();
//是文件名处于当前目录下
fileName = "." + fileName ;
//打开请求的文件
FileInputStream fis = null ;
boolean fileExists = true ;
if (fileName=="./") {
fileName="./index.html";
System.out.println("FILENAME " + fileName);
}
try {
fis = new FileInputStream(fileName);
} catch (FileNotFoundException e) {
fileExists = false ;
}
// DEBUG 信息
System.out.println("Incoming!!!");
System.out.println(requestLine);
String headerLine = null;
while ((headerLine = br.readLine()).length() != 0) {
System.out.println(headerLine);
}
//构造回应信息
String statusLine = null;
String contentTypeLine = null;
String entityBody = null;
if (fileExists) {
statusLine = "HTTP/1.0 200 OK" + CRLF;
contentTypeLine = "Content-Type: " +
contentType(fileName) + CRLF;
} else {
statusLine = "HTTP/1.0 404 Not Found" + CRLF;
contentTypeLine = "Content-Type: text/html" + CRLF;
entityBody = "<HTML>" +
"<HEAD><TITLE>Not Found</TITLE></HEAD>" +
"<BODY>Not Found</BODY></HTML>";
}
os.writeBytes(statusLine);
os.writeBytes(contentTypeLine);
os.writeBytes(CRLF);
if (fileExists) {
sendBytes(fis, os);
fis.close();
} else {
os.writeBytes(entityBody) ;
}
//关闭流与包
os.close();
br.close();
socket.close();
}
private static void sendBytes(FileInputStream fis,
OutputStream os) throws Exception {
byte[] buffer = new byte[1024];
int bytes = 0;
while ((bytes = fis.read(buffer)) != -1) {
os.write(buffer, 0, bytes);
}
}
private static String contentType(String fileName) {
if(fileName.endsWith(".htm") || fileName.endsWith(".html")) {
return "text/html";
}
if(fileName.endsWith(".ram") || fileName.endsWith(".ra")) {
return "audio/x-pn-realaudio";
}
return "application/octet-stream" ;
}
}