Solutions for Programming Assignment 1
Below are the solutions for the Web Server lab. There are two classes, HttpRequest and WebServer.
HttpRequest.java
import java.io.* ;
import java.net.* ;
import java.util.* ;
final class HttpRequest implements Runnable {
final static String CRLF = "\r\n"; //Carriage Return Line Feed 姿态返回线路管道
Socket socket;
// Constructor 构造函数
public HttpRequest(Socket socket) throws Exception {
this.socket = socket;
}
// Implement the run() method of the Runnable interface. 继承
public void run() {
try {
processRequest();
} catch (Exception e) {
System.out.println(e);
}
}
private void processRequest() throws Exception {
// Get a reference to the socket's input and output streams. 获取引用
InputStream is = socket.getInputStream();
DataOutputStream os = new DataOutputStream(socket.getOutputStream());
// Set up input stream filters. 设置输入流过滤器
BufferedReader br = new BufferedReader(new InputStreamReader(is));
// Get the request line of the HTTP request message. 获取http请求信息的请求行
String requestLine = br.readLine();
// Extract the filename from the request line. 从请求行提取文件名
StringTokenizer tokens = new StringTokenizer(requestLine);
tokens.nextToken(); // skip over the method, which should be "GET"
String fileName = tokens.nextToken();
// Prepend a "." so that file request is within the current directory. 预先挂起 以使文件请求范围设定在当前文件目录内
fileName = "." + fileName ;
// Open the requested file. 打开请求文件
FileInputStream fis = null ;
boolean fileExists = true ;
try {
fis = new FileInputStream(fileName);
} catch (FileNotFoundException e) {
fileExists = false ;
}
// Debug info for private use 检测信息为了私用
System.out.println("Incoming!!!");
System.out.println(requestLine);
String headerLine = null;
while ((headerLine = br.readLine()).length() != 0) {
System.out.println(headerLine);
}
// Construct the response message. 构造反馈信息
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>";
}
// Send the status line. 发送状态行
os.writeBytes(statusLine);
// Send the content type line. 发送内容类型行
os.writeBytes(contentTypeLine);
// Send a blank line to indicate the end of the header lines. 发送一个空行去指明 头行的终点
os.writeBytes(CRLF);
// Send the entity body. 发送实体的主体
if (fileExists) {
sendBytes(fis, os);
fis.close();
} else {
os.writeBytes(entityBody) ;
}
// Close streams and socket. 关闭流和socket通道
os.close();
br.close();
socket.close();
}
private static void sendBytes(FileInputStream fis,
OutputStream os) throws Exception {
// Construct a 1K buffer to hold bytes on their way to the socket. 构造一个1k字节大小的缓冲 去承载通向socket的字节
byte[] buffer = new byte[1024];
int bytes = 0;
// Copy requested file into the socket's output stream. 复制请求的文件 到socket的输出流
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" ;
}
}
WebServer.java
import java.io.* ;
import java.net.* ;
import java.util.* ;
public final class WebServer {
public static void main(String argv[]) throws Exception {
// Get the port number from the command line. 从命令行获取端口号
int port = (new Integer(argv[0])).intValue();
// Establish the listen socket. 建立监听端口
ServerSocket socket = new ServerSocket(port);
// Process HTTP service requests in an infinite loop. 处理http服务请求在一个无线循环中
while (true) {
// Listen for a TCP connection request. 监听 tcp连接请求
Socket connection = socket.accept();
// Construct an object to process the HTTP request message. 构造一个对象去处理http请求信息
HttpRequest request = new HttpRequest(connection);
// Create a new thread to process the request. 创造一个新的线程去处理请求
Thread thread = new Thread(request);
// Start the thread. 启动这个线程
thread.start();
}
}
}
Solutions for Programming Assignment 1Below are the solutions for the Web Server lab. There are two classes, HttpRequest and WebServer. HttpRequest.java import java.io.* ;import java.n