用 Java 来打造属于自己的Web服务器

很久很久以前,没有web服务器的概念,就知道在windows下配置一下IIS,用来跑asp。到后来的asp.net也还是IIS。接着又接触到java,于是知道了还有apache和tomcat。然后是php,也还是和apache在打交道。直至某一天,我又知道了这个世界上还有俄罗斯人写的优秀的nginx,以及lighttpd等web服务器。

一直以来,我都以为web服务器是一个非常复杂的系统,需要有着高深的理论知识才能去写这么一个软件,它应该是一个团队才可以应付的事情。当然,也想过它的工作原理,无非是绑定一个端口,然后处理web请求并做出相应的响应。不过,始终都认为那应该是一件神奇的事情,不是我等凡夫俗子可以对付得了。

这两天对各种服务器的配置都做了一些了解,对于写web服务器的冲动又一下子涌上心头了。最开始想用c,于是便下载了一个有若干年没有碰过的tc,稍微调试了一番,发现还缺少很多头文件,一时半会还找不全;而对于c++,又觉得过于繁杂,不想去碰它;c#的话,总感觉微软的东东过于庞大臃肿,也不想理会;于是,自然而然就想到了java。

很简单地,最开始肯定是用socket绑定一个端口,接下来试着从浏览器访问这个端口。没想到,还真能将请求发到这个socket里头来,把请求内容输出以后,发现正是http协议的标准写法,熟悉的GET / HTTP/1.1\r\n 映入了眼帘。在这一刻,我似乎对于web这一回事又有了一个更深刻的认识。浏览器只不过按照http协议的要求,把请求封装成标准格式,打包发送到web服务器上。web服务器将请求收集起来,按照http协议的规定将请求解析,然后把对应的内容找到,又一次按照http协议的要求封装起来,返回给浏览器端。浏览器接下来把这些返回的内容解析,并渲染出来。这些流程,以前也有很多次见识过,不过,总还是感觉有些抽象。不过,今天这样随便一写,却感觉这一切都变得那么具体和熟悉起来。

对于请求的处理,需要涉及到多线程,因此干脆从网上搜索了一篇文章: WebServer.java 用JAVA编写Web服务器,并对其进行了相应的修改,使得扩展性和可读性更强。在这篇文章的基础上,加入了两个新类——PageRequest和PageResponse,分别用来处理请求和响应。

ContractedBlock.gif ExpandedBlockStart.gif Code
None.gif//AnyWebServer.java  用JAVA编写Web服务器
None.gif
import java.io.DataInputStream;
None.gif
import java.io.File;
None.gif
import java.io.FileInputStream;
None.gif
import java.io.IOException;
None.gif
import java.io.PrintStream;
None.gif
import java.net.ServerSocket;
None.gif
import java.net.Socket;
None.gif
import java.util.Date;
None.gif
import java.util.HashMap;
None.gif
ExpandedBlockStart.gifContractedBlock.gif
public class AnyWebServer dot.gif{
ExpandedSubBlockStart.gifContractedSubBlock.gif    
public static void main(String args[]) dot.gif{
InBlock.gif        
int i = 1, PORT = 1300;
InBlock.gif        ServerSocket server 
= null;
InBlock.gif        Socket client 
= null;
ExpandedSubBlockStart.gifContractedSubBlock.gif        
try dot.gif{
InBlock.gif            server 
= new ServerSocket(PORT);
InBlock.gif            System.out.println(
"Web Server is listening on port "
InBlock.gif                    
+ server.getLocalPort());
ExpandedSubBlockStart.gifContractedSubBlock.gif            
for (;;) dot.gif{
InBlock.gif                client 
= server.accept(); // 接受客户机的连接请求
InBlock.gif
                new ConnectionThread(client, i).start();
InBlock.gif                i
++;
ExpandedSubBlockEnd.gif            }

ExpandedSubBlockStart.gifContractedSubBlock.gif        }
 catch (Exception e) dot.gif{
InBlock.gif            System.out.println(e);
ExpandedSubBlockEnd.gif        }

ExpandedSubBlockEnd.gif    }

ExpandedBlockEnd.gif}

None.gif
ExpandedBlockStart.gifContractedBlock.gif
/**//* ConnnectionThread类完成与一个Web浏览器的通信 */
ExpandedBlockStart.gifContractedBlock.gif
class ConnectionThread extends Thread dot.gif{
InBlock.gif    
// 网站根目录
InBlock.gif
    private static final String WEB_ROOT = "d:\\workspace\\anyws\\site\\";
InBlock.gif    Socket client; 
// 连接Web浏览器的socket字
InBlock.gif
    int counter; // 计数器
InBlock.gif

ExpandedSubBlockStart.gifContractedSubBlock.gif    
public ConnectionThread(Socket cl, int c) dot.gif{
InBlock.gif        client 
= cl;
InBlock.gif        counter 
= c;
ExpandedSubBlockEnd.gif    }

InBlock.gif
InBlock.gif    
public void run() // 线程体
ExpandedSubBlockStart.gifContractedSubBlock.gif
    dot.gif{
ExpandedSubBlockStart.gifContractedSubBlock.gif        
try dot.gif{
InBlock.gif            String destIP 
= client.getInetAddress().toString(); // 客户机IP地址
InBlock.gif
            int destport = client.getPort(); // 客户机端口号
InBlock.gif
            System.out.println("Connection " + counter + ":connected to "
InBlock.gif                    
+ destIP + " on port " + destport + ".");
InBlock.gif            PrintStream outstream 
= new PrintStream(client.getOutputStream());
InBlock.gif            DataInputStream instream 
= new DataInputStream(client
InBlock.gif                    .getInputStream());
InBlock.gif            
InBlock.gif            PageRequest req 
= new PageRequest(instream);
InBlock.gif            req.init();
InBlock.gif            System.out.println(
"Received:" + req.getMethod() + " " + req.getFile() + " " + req.getVersion());
ExpandedSubBlockStart.gifContractedSubBlock.gif            
if (req.getMethod().equalsIgnoreCase("GET")) dot.gif// 如果是GET请求
InBlock.gif
                String filename = req.getFile();
InBlock.gif                
if (filename.equals("/")) filename = "index.html";
InBlock.gif                File file 
= new File(WEB_ROOT + filename);
InBlock.gif                PageResponse res 
= new PageResponse(outstream);
ExpandedSubBlockStart.gifContractedSubBlock.gif                
if (file.exists()) dot.gif// 若文件存在,则将文件送给Web浏览器
InBlock.gif
                    System.out.println(filename + " requested.");
InBlock.gif                    
InBlock.gif                    
long lastModified = file.lastModified();
InBlock.gif                    String eTag 
= String.valueOf(lastModified);
InBlock.gif                    res.addHeader(
"ETag", eTag);
ExpandedSubBlockStart.gifContractedSubBlock.gif                    
if (eTag.equals(req.getHeader("If-None-Match"))) dot.gif{
InBlock.gif                        res.setStatus(
304);
ExpandedSubBlockStart.gifContractedSubBlock.gif                    }
 else dot.gif{
InBlock.gif                        
int len = (int) file.length();
InBlock.gif                        res.addHeader(
"Content-Length", String.valueOf(len));
InBlock.gif                        Date now 
= new Date();
InBlock.gif                        res.addHeader(
"Date", now.toString());
InBlock.gif                        res.addHeader(
"Expires"new Date(
InBlock.gif                                now.getTime() 
+ 3600 * 24 * 1000).toString());
InBlock.gif                        res.appendFile(file);
ExpandedSubBlockEnd.gif                    }

ExpandedSubBlockStart.gifContractedSubBlock.gif                }
 else dot.gif// 文件不存在时
InBlock.gif
                    System.out.println(filename + " not exist.");
InBlock.gif                    String msg 
= "<html><head><title>Not Found</title></head><body><h1>HTTP/1.0 404 not found</h1></body></html>";
InBlock.gif                    res.setStatus(
404);
InBlock.gif                    res.addHeader(
"Content-type""text/html");
InBlock.gif                    res.addHeader(
"Content-Length", String
InBlock.gif                            .valueOf(msg.length() 
+ 2));
InBlock.gif                    res.write(msg);
ExpandedSubBlockEnd.gif                }

InBlock.gif                res.flush();
ExpandedSubBlockEnd.gif            }

InBlock.gif             instream.close();
InBlock.gif             outstream.close();
InBlock.gif            
long m1 = 1// 延时
ExpandedSubBlockStart.gifContractedSubBlock.gif
            while (m1 < 11100000dot.gif{
InBlock.gif                m1
++;
ExpandedSubBlockEnd.gif            }

InBlock.gif            client.close();
ExpandedSubBlockStart.gifContractedSubBlock.gif        }
 catch (IOException e) dot.gif{
InBlock.gif            System.out.println(
"Exception:" + e);
ExpandedSubBlockEnd.gif        }

ExpandedSubBlockEnd.gif    }

ExpandedBlockEnd.gif}

None.gif
ExpandedBlockStart.gifContractedBlock.gif
/** *//**
InBlock.gif * 页面请求类
InBlock.gif * 
@author Administrator
InBlock.gif *
ExpandedBlockEnd.gif 
*/

ExpandedBlockStart.gifContractedBlock.gif
class PageRequest dot.gif{
InBlock.gif    
private DataInputStream in;
ExpandedSubBlockStart.gifContractedSubBlock.gif    
public PageRequest(DataInputStream in) dot.gif{
InBlock.gif        
this.in = in;
ExpandedSubBlockEnd.gif    }

InBlock.gif    
private HashMap<String, String> headers = new HashMap<String, String>();
InBlock.gif    
InBlock.gif    
private String method;
ExpandedSubBlockStart.gifContractedSubBlock.gif    
/** *//**
InBlock.gif     * 请求方法
InBlock.gif     * 
@return
ExpandedSubBlockEnd.gif     
*/

ExpandedSubBlockStart.gifContractedSubBlock.gif    
public String getMethod() dot.gif{
InBlock.gif        
return this.method;
ExpandedSubBlockEnd.gif    }

InBlock.gif
InBlock.gif    
private String file;
ExpandedSubBlockStart.gifContractedSubBlock.gif    
public String getFile() dot.gif{
InBlock.gif        
return this.file;
ExpandedSubBlockEnd.gif    }

InBlock.gif    
InBlock.gif    
private String version;
ExpandedSubBlockStart.gifContractedSubBlock.gif    
public String getVersion() dot.gif{
InBlock.gif        
return this.version;
ExpandedSubBlockEnd.gif    }

InBlock.gif    
InBlock.gif    @SuppressWarnings(
"deprecation")
ExpandedSubBlockStart.gifContractedSubBlock.gif    
public void init() dot.gif{
ExpandedSubBlockStart.gifContractedSubBlock.gif        
try dot.gif{
InBlock.gif            String firstLine 
= in.readLine();
InBlock.gif            String[] arr 
= firstLine.split(" ");
InBlock.gif            method 
= arr[0];
InBlock.gif            file 
= arr[1];
InBlock.gif            version 
= arr[2];
InBlock.gif            
InBlock.gif            String line 
= null;
ExpandedSubBlockStart.gifContractedSubBlock.gif            
while (!(line = in.readLine()).equals("")) dot.gif{
InBlock.gif                arr 
= line.split("");
InBlock.gif                headers.put(arr[
0], arr[1]);
ExpandedSubBlockEnd.gif            }

InBlock.gif            
InBlock.gif            System.out.print(line);
InBlock.gif            
//TODO
ExpandedSubBlockStart.gifContractedSubBlock.gif
        }
 catch (IOException e) dot.gif{
InBlock.gif            
// TODO Auto-generated catch block
InBlock.gif
            e.printStackTrace();
ExpandedSubBlockEnd.gif        }

ExpandedSubBlockEnd.gif    }

ExpandedSubBlockStart.gifContractedSubBlock.gif    
/** *//**
InBlock.gif     * 获取请求头
InBlock.gif     * 
@param key
InBlock.gif     * 
@return
ExpandedSubBlockEnd.gif     
*/

ExpandedSubBlockStart.gifContractedSubBlock.gif    
public String getHeader(String key) dot.gif{
InBlock.gif        
return headers.get(key);
ExpandedSubBlockEnd.gif    }

ExpandedBlockEnd.gif}

None.gif
ExpandedBlockStart.gifContractedBlock.gif
/** *//**
InBlock.gif * 页面响应类
InBlock.gif * 
InBlock.gif * 
@author Administrator
ExpandedBlockEnd.gif 
*/

ExpandedBlockStart.gifContractedBlock.gif
class PageResponse dot.gif{
InBlock.gif    
private PrintStream ps;
ExpandedSubBlockStart.gifContractedSubBlock.gif    
/** *//**
InBlock.gif     * 页面响应头
ExpandedSubBlockEnd.gif     
*/

InBlock.gif    
private HashMap<String, String> headers = new HashMap<String, String>();
InBlock.gif    
private static HashMap<Integer, String> codes = null;
InBlock.gif    
private StringBuffer content = new StringBuffer();
InBlock.gif    
private int code = 200;
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif    
public PageResponse(PrintStream ps) dot.gif{
InBlock.gif        
this.ps = ps;
InBlock.gif
InBlock.gif        initHeader();
InBlock.gif        initCodes();
ExpandedSubBlockEnd.gif    }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif    
private void initHeader() dot.gif{
InBlock.gif        headers.put(
"Server""Deng Web Server");
InBlock.gif        headers.put(
"Date"new Date().toString());
ExpandedSubBlockEnd.gif    }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif    
private void initCodes() dot.gif{
ExpandedSubBlockStart.gifContractedSubBlock.gif        
if (codes == nulldot.gif{
InBlock.gif            codes 
= new HashMap<Integer, String>();
InBlock.gif            codes.put(
200"OK");
InBlock.gif            codes.put(
304"Not Modified");
InBlock.gif            codes.put(
400"Not Found");
InBlock.gif            codes.put(
401"Unauthorized");
InBlock.gif            codes.put(
402"Payment Required");
InBlock.gif            codes.put(
403"Forbidden");
InBlock.gif            codes.put(
500"Internal Server Error");
ExpandedSubBlockEnd.gif        }

ExpandedSubBlockEnd.gif    }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif    
/** *//**
InBlock.gif     * 设置响应状态值
InBlock.gif     * 
InBlock.gif     * 
@param code
ExpandedSubBlockEnd.gif     
*/

ExpandedSubBlockStart.gifContractedSubBlock.gif    
public void setStatus(int code) dot.gif{
InBlock.gif        
this.code = code;
ExpandedSubBlockEnd.gif    }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif    
/** *//**
InBlock.gif     * 添加响应头
InBlock.gif     * 
InBlock.gif     * 
@param key
InBlock.gif     * 
@param value
ExpandedSubBlockEnd.gif     
*/

ExpandedSubBlockStart.gifContractedSubBlock.gif    
public void addHeader(String key, String value) dot.gif{
InBlock.gif        headers.put(key, value);
ExpandedSubBlockEnd.gif    }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif    
/** *//**
InBlock.gif     * 添加内容
InBlock.gif     * 
InBlock.gif     * 
@param str
ExpandedSubBlockEnd.gif     
*/

ExpandedSubBlockStart.gifContractedSubBlock.gif    
public void write(String str) dot.gif{
InBlock.gif        content.append(str);
ExpandedSubBlockEnd.gif    }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif    
/** *//**
InBlock.gif     * 将页面内容输出
ExpandedSubBlockEnd.gif     
*/

ExpandedSubBlockStart.gifContractedSubBlock.gif    
public void flush() dot.gif{
InBlock.gif        ps.println(
"HTTP/1.1 " + code + " " + codes.get(code) + "\r");
ExpandedSubBlockStart.gifContractedSubBlock.gif        
for (String key : headers.keySet()) dot.gif{
InBlock.gif            ps.println(key 
+ ":" + headers.get(key));
ExpandedSubBlockEnd.gif        }

InBlock.gif        ps.println();
InBlock.gif        ps.print(content.toString());
InBlock.gif        ps.flush();
ExpandedSubBlockEnd.gif    }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif    
/** *//**
InBlock.gif     * 输出文件
InBlock.gif     * 
InBlock.gif     * 
@param file
ExpandedSubBlockEnd.gif     
*/

ExpandedSubBlockStart.gifContractedSubBlock.gif    
public void appendFile(File file) dot.gif{
ExpandedSubBlockStart.gifContractedSubBlock.gif        
try dot.gif{
InBlock.gif            DataInputStream in 
= new DataInputStream(new FileInputStream(file));
InBlock.gif            
int len = (int) file.length();
InBlock.gif            
byte buf[] = new byte[len];
InBlock.gif            in.readFully(buf);
InBlock.gif            content.append(
new String(buf, 0, len));
InBlock.gif            in.close();
ExpandedSubBlockStart.gifContractedSubBlock.gif        }
 catch (Exception e) dot.gif{
InBlock.gif            System.out.println(
"Error retrieving file.");
InBlock.gif            System.exit(
1);
ExpandedSubBlockEnd.gif        }

ExpandedSubBlockEnd.gif    }

ExpandedBlockEnd.gif}



None.gif//WebServer.java  用JAVA编写Web服务器
None.gif
import java.io.DataInputStream;
None.gif
import java.io.File;
None.gif
import java.io.FileInputStream;
None.gif
import java.io.IOException;
None.gif
import java.io.PrintStream;
None.gif
import java.net.ServerSocket;
None.gif
import java.net.Socket;
None.gif
import java.util.Date;
None.gif
import java.util.HashMap;
None.gif
ExpandedBlockStart.gifContractedBlock.gif
public class AnyWebServer dot.gif{
ExpandedSubBlockStart.gifContractedSubBlock.gif    
public static void main(String args[]) dot.gif{
InBlock.gif        
int i = 1, PORT = 1300;
InBlock.gif        ServerSocket server 
= null;
InBlock.gif        Socket client 
= null;
ExpandedSubBlockStart.gifContractedSubBlock.gif        
try dot.gif{
InBlock.gif            server 
= new ServerSocket(PORT);
InBlock.gif            System.out.println(
"Web Server is listening on port "
InBlock.gif                    
+ server.getLocalPort());
ExpandedSubBlockStart.gifContractedSubBlock.gif            
for (;;) dot.gif{
InBlock.gif                client 
= server.accept(); // 接受客户机的连接请求
InBlock.gif
                new ConnectionThread(client, i).start();
InBlock.gif                i
++;
ExpandedSubBlockEnd.gif            }

ExpandedSubBlockStart.gifContractedSubBlock.gif        }
 catch (Exception e) dot.gif{
InBlock.gif            System.out.println(e);
ExpandedSubBlockEnd.gif        }

ExpandedSubBlockEnd.gif    }

ExpandedBlockEnd.gif}

None.gif
ExpandedBlockStart.gifContractedBlock.gif
/**//* ConnnectionThread类完成与一个Web浏览器的通信 */
ExpandedBlockStart.gifContractedBlock.gif
class ConnectionThread extends Thread dot.gif{
InBlock.gif    
// 网站根目录
InBlock.gif
    private static final String WEB_ROOT = "d:\\workspace\\anyws\\site\\";
InBlock.gif    Socket client; 
// 连接Web浏览器的socket字
InBlock.gif
    int counter; // 计数器
InBlock.gif

ExpandedSubBlockStart.gifContractedSubBlock.gif    
public ConnectionThread(Socket cl, int c) dot.gif{
InBlock.gif        client 
= cl;
InBlock.gif        counter 
= c;
ExpandedSubBlockEnd.gif    }

InBlock.gif
InBlock.gif    
public void run() // 线程体
ExpandedSubBlockStart.gifContractedSubBlock.gif
    dot.gif{
ExpandedSubBlockStart.gifContractedSubBlock.gif        
try dot.gif{
InBlock.gif            String destIP 
= client.getInetAddress().toString(); // 客户机IP地址
InBlock.gif
            int destport = client.getPort(); // 客户机端口号
InBlock.gif
            System.out.println("Connection " + counter + ":connected to "
InBlock.gif                    
+ destIP + " on port " + destport + ".");
InBlock.gif            PrintStream outstream 
= new PrintStream(client.getOutputStream());
InBlock.gif            DataInputStream instream 
= new DataInputStream(client
InBlock.gif                    .getInputStream());
InBlock.gif            
InBlock.gif            PageRequest req 
= new PageRequest(instream);
InBlock.gif            req.init();
InBlock.gif            System.out.println(
"Received:" + req.getMethod() + " " + req.getFile() + " " + req.getVersion());
ExpandedSubBlockStart.gifContractedSubBlock.gif            
if (req.getMethod().equalsIgnoreCase("GET")) dot.gif// 如果是GET请求
InBlock.gif
                String filename = req.getFile();
InBlock.gif                
if (filename.equals("/")) filename = "index.html";
InBlock.gif                File file 
= new File(WEB_ROOT + filename);
InBlock.gif                PageResponse res 
= new PageResponse(outstream);
ExpandedSubBlockStart.gifContractedSubBlock.gif                
if (file.exists()) dot.gif// 若文件存在,则将文件送给Web浏览器
InBlock.gif
                    System.out.println(filename + " requested.");
InBlock.gif                    
InBlock.gif                    
long lastModified = file.lastModified();
InBlock.gif                    String eTag 
= String.valueOf(lastModified);
InBlock.gif                    res.addHeader(
"ETag", eTag);
ExpandedSubBlockStart.gifContractedSubBlock.gif                    
if (eTag.equals(req.getHeader("If-None-Match"))) dot.gif{
InBlock.gif                        res.setStatus(
304);
ExpandedSubBlockStart.gifContractedSubBlock.gif                    }
 else dot.gif{
InBlock.gif                        
int len = (int) file.length();
InBlock.gif                        res.addHeader(
"Content-Length", String.valueOf(len));
InBlock.gif                        Date now 
= new Date();
InBlock.gif                        res.addHeader(
"Date", now.toString());
InBlock.gif                        res.addHeader(
"Expires"new Date(
InBlock.gif                                now.getTime() 
+ 3600 * 24 * 1000).toString());
InBlock.gif                        res.appendFile(file);
ExpandedSubBlockEnd.gif                    }

ExpandedSubBlockStart.gifContractedSubBlock.gif                }
 else dot.gif// 文件不存在时
InBlock.gif
                    System.out.println(filename + " not exist.");
InBlock.gif                    String msg 
= "<html><head><title>Not Found</title></head><body><h1>HTTP/1.0 404 not found</h1></body></html>";
InBlock.gif                    res.setStatus(
404);
InBlock.gif                    res.addHeader(
"Content-type""text/html");
InBlock.gif                    res.addHeader(
"Content-Length", String
InBlock.gif                            .valueOf(msg.length() 
+ 2));
InBlock.gif                    res.write(msg);
ExpandedSubBlockEnd.gif                }

InBlock.gif                res.flush();
ExpandedSubBlockEnd.gif            }

InBlock.gif             instream.close();
InBlock.gif             outstream.close();
InBlock.gif            
long m1 = 1// 延时
ExpandedSubBlockStart.gifContractedSubBlock.gif
            while (m1 < 11100000dot.gif{
InBlock.gif                m1
++;
ExpandedSubBlockEnd.gif            }

InBlock.gif            client.close();
ExpandedSubBlockStart.gifContractedSubBlock.gif        }
 catch (IOException e) dot.gif{
InBlock.gif            System.out.println(
"Exception:" + e);
ExpandedSubBlockEnd.gif        }

ExpandedSubBlockEnd.gif    }

ExpandedBlockEnd.gif}

None.gif
ExpandedBlockStart.gifContractedBlock.gif
/** *//**
InBlock.gif * 页面请求类
InBlock.gif * 
@author Administrator
InBlock.gif *
ExpandedBlockEnd.gif 
*/

ExpandedBlockStart.gifContractedBlock.gif
class PageRequest dot.gif{
InBlock.gif    
private DataInputStream in;
ExpandedSubBlockStart.gifContractedSubBlock.gif    
public PageRequest(DataInputStream in) dot.gif{
InBlock.gif        
this.in = in;
ExpandedSubBlockEnd.gif    }

InBlock.gif    
private HashMap<String, String> headers = new HashMap<String, String>();
InBlock.gif    
InBlock.gif    
private String method;
ExpandedSubBlockStart.gifContractedSubBlock.gif    
/** *//**
InBlock.gif     * 请求方法
InBlock.gif     * 
@return
ExpandedSubBlockEnd.gif     
*/

ExpandedSubBlockStart.gifContractedSubBlock.gif    
public String getMethod() dot.gif{
InBlock.gif        
return this.method;
ExpandedSubBlockEnd.gif    }

InBlock.gif
InBlock.gif    
private String file;
ExpandedSubBlockStart.gifContractedSubBlock.gif    
public String getFile() dot.gif{
InBlock.gif        
return this.file;
ExpandedSubBlockEnd.gif    }

InBlock.gif    
InBlock.gif    
private String version;
ExpandedSubBlockStart.gifContractedSubBlock.gif    
public String getVersion() dot.gif{
InBlock.gif        
return this.version;
ExpandedSubBlockEnd.gif    }

InBlock.gif    
InBlock.gif    @SuppressWarnings(
"deprecation")
ExpandedSubBlockStart.gifContractedSubBlock.gif    
public void init() dot.gif{
ExpandedSubBlockStart.gifContractedSubBlock.gif        
try dot.gif{
InBlock.gif            String firstLine 
= in.readLine();
InBlock.gif            String[] arr 
= firstLine.split(" ");
InBlock.gif            method 
= arr[0];
InBlock.gif            file 
= arr[1];
InBlock.gif            version 
= arr[2];
InBlock.gif            
InBlock.gif            String line 
= null;
ExpandedSubBlockStart.gifContractedSubBlock.gif            
while (!(line = in.readLine()).equals("")) dot.gif{
InBlock.gif                arr 
= line.split("");
InBlock.gif                headers.put(arr[
0], arr[1]);
ExpandedSubBlockEnd.gif            }

InBlock.gif            
InBlock.gif            System.out.print(line);
InBlock.gif            
//TODO
ExpandedSubBlockStart.gifContractedSubBlock.gif
        }
 catch (IOException e) dot.gif{
InBlock.gif            
// TODO Auto-generated catch block
InBlock.gif
            e.printStackTrace();
ExpandedSubBlockEnd.gif        }

ExpandedSubBlockEnd.gif    }

ExpandedSubBlockStart.gifContractedSubBlock.gif    
/** *//**
InBlock.gif     * 获取请求头
InBlock.gif     * 
@param key
InBlock.gif     * 
@return
ExpandedSubBlockEnd.gif     
*/

ExpandedSubBlockStart.gifContractedSubBlock.gif    
public String getHeader(String key) dot.gif{
InBlock.gif        
return headers.get(key);
ExpandedSubBlockEnd.gif    }

ExpandedBlockEnd.gif}

None.gif
ExpandedBlockStart.gifContractedBlock.gif
/** *//**
InBlock.gif * 页面响应类
InBlock.gif * 
InBlock.gif * 
@author Administrator
ExpandedBlockEnd.gif 
*/

ExpandedBlockStart.gifContractedBlock.gif
class PageResponse dot.gif{
InBlock.gif    
private PrintStream ps;
ExpandedSubBlockStart.gifContractedSubBlock.gif    
/** *//**
InBlock.gif     * 页面响应头
ExpandedSubBlockEnd.gif     
*/

InBlock.gif    
private HashMap<String, String> headers = new HashMap<String, String>();
InBlock.gif    
private static HashMap<Integer, String> codes = null;
InBlock.gif    
private StringBuffer content = new StringBuffer();
InBlock.gif    
private int code = 200;
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif    
public PageResponse(PrintStream ps) dot.gif{
InBlock.gif        
this.ps = ps;
InBlock.gif
InBlock.gif        initHeader();
InBlock.gif        initCodes();
ExpandedSubBlockEnd.gif    }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif    
private void initHeader() dot.gif{
InBlock.gif        headers.put(
"Server""Deng Web Server");
InBlock.gif        headers.put(
"Date"new Date().toString());
ExpandedSubBlockEnd.gif    }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif    
private void initCodes() dot.gif{
ExpandedSubBlockStart.gifContractedSubBlock.gif        
if (codes == nulldot.gif{
InBlock.gif            codes 
= new HashMap<Integer, String>();
InBlock.gif            codes.put(
200"OK");
InBlock.gif            codes.put(
304"Not Modified");
InBlock.gif            codes.put(
400"Not Found");
InBlock.gif            codes.put(
401"Unauthorized");
InBlock.gif            codes.put(
402"Payment Required");
InBlock.gif            codes.put(
403"Forbidden");
InBlock.gif            codes.put(
500"Internal Server Error");
ExpandedSubBlockEnd.gif        }

ExpandedSubBlockEnd.gif    }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif    
/** *//**
InBlock.gif     * 设置响应状态值
InBlock.gif     * 
InBlock.gif     * 
@param code
ExpandedSubBlockEnd.gif     
*/

ExpandedSubBlockStart.gifContractedSubBlock.gif    
public void setStatus(int code) dot.gif{
InBlock.gif        
this.code = code;
ExpandedSubBlockEnd.gif    }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif    
/** *//**
InBlock.gif     * 添加响应头
InBlock.gif     * 
InBlock.gif     * 
@param key
InBlock.gif     * 
@param value
ExpandedSubBlockEnd.gif     
*/

ExpandedSubBlockStart.gifContractedSubBlock.gif    
public void addHeader(String key, String value) dot.gif{
InBlock.gif        headers.put(key, value);
ExpandedSubBlockEnd.gif    }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif    
/** *//**
InBlock.gif     * 添加内容
InBlock.gif     * 
InBlock.gif     * 
@param str
ExpandedSubBlockEnd.gif     
*/

ExpandedSubBlockStart.gifContractedSubBlock.gif    
public void write(String str) dot.gif{
InBlock.gif        content.append(str);
ExpandedSubBlockEnd.gif    }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif    
/** *//**
InBlock.gif     * 将页面内容输出
ExpandedSubBlockEnd.gif     
*/

ExpandedSubBlockStart.gifContractedSubBlock.gif    
public void flush() dot.gif{
InBlock.gif        ps.println(
"HTTP/1.1 " + code + " " + codes.get(code) + "\r");
ExpandedSubBlockStart.gifContractedSubBlock.gif        
for (String key : headers.keySet()) dot.gif{
InBlock.gif            ps.println(key 
+ ":" + headers.get(key));
ExpandedSubBlockEnd.gif        }

InBlock.gif        ps.println();
InBlock.gif        ps.print(content.toString());
InBlock.gif        ps.flush();
ExpandedSubBlockEnd.gif    }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif    
/** *//**
InBlock.gif     * 输出文件
InBlock.gif     * 
InBlock.gif     * 
@param file
ExpandedSubBlockEnd.gif     
*/

ExpandedSubBlockStart.gifContractedSubBlock.gif    
public void appendFile(File file) dot.gif{
ExpandedSubBlockStart.gifContractedSubBlock.gif        
try dot.gif{
InBlock.gif            DataInputStream in 
= new DataInputStream(new FileInputStream(file));
InBlock.gif            
int len = (int) file.length();
InBlock.gif            
byte buf[] = new byte[len];
InBlock.gif            in.readFully(buf);
InBlock.gif            content.append(
new String(buf, 0, len));
InBlock.gif            in.close();
ExpandedSubBlockStart.gifContractedSubBlock.gif        }
 catch (Exception e) dot.gif{
InBlock.gif            System.out.println(
"Error retrieving file.");
InBlock.gif            System.exit(
1);
ExpandedSubBlockEnd.gif        }

ExpandedSubBlockEnd.gif    }

ExpandedBlockEnd.gif}

转载于:https://www.cnblogs.com/comdeng/archive/2008/10/08/1305978.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值