手机版
你好,游客 登录 注册
背景:
阅读新闻

用Java编写你自己的简单HTTP服务器

[日期:2012-02-27] 来源:Linux社区  作者:yanghua_kobe [字体:大 中 小]

JHTTP类的main()方法根据args[0]设置文档的根目录。端口从args[1]读取,或者使用默认的80.然后构造一个新的JHTTP线程并启动。此JHTTP线程生成50个RequestProcessor线程处理请求,每个线程在可用时从RequestProcessor池获取入站连接请求。JHTTP线程反复地接受入站连接,并将其放在RequestProcessor池中。每个连接由下例所示的RequestProcessor类的run()方法处理。此方法将一直等待,直到从池中得到一个Socket。一旦得到Socket,就获取输入和输出流,并链接到阅读器和书写器。接着的处理,除了多出文档目录、路径的处理,其他的同单文件服务器。

  1. import Java.io.BufferedInputStream;  
  2. import java.io.BufferedOutputStream;  
  3. import java.io.DataInputStream;  
  4. import java.io.File;  
  5. import java.io.FileInputStream;  
  6. import java.io.IOException;  
  7. import java.io.InputStreamReader;  
  8. import java.io.OutputStream;  
  9. import java.io.OutputStreamWriter;  
  10. import java.io.Reader;  
  11. import java.io.Writer;  
  12. import java.net.Socket;  
  13. import java.util.Date;  
  14. import java.util.List;  
  15. import java.util.LinkedList;  
  16. import java.util.StringTokenizer;  
  17.   
  18.   
  19. public class RequestProcessor implements Runnable {  
  20.   
  21.     private static List pool=new LinkedList();  
  22.     private File documentRootDirectory;  
  23.     private String indexFileName="index.html";  
  24.       
  25.     public RequestProcessor(File documentRootDirectory,String indexFileName) {  
  26.         if (documentRootDirectory.isFile()) {  
  27.             throw new IllegalArgumentException();  
  28.         }  
  29.         this.documentRootDirectory=documentRootDirectory;  
  30.         try {  
  31.             this.documentRootDirectory=documentRootDirectory.getCanonicalFile();  
  32.         } catch (IOException e) {  
  33.         }  
  34.           
  35.         if (indexFileName!=null) {  
  36.             this.indexFileName=indexFileName;  
  37.         }  
  38.     }  
  39.       
  40.     public static void processRequest(Socket request) {  
  41.         synchronized (pool) {  
  42.             pool.add(pool.size(),request);  
  43.             pool.notifyAll();  
  44.         }  
  45.     }  
  46.       
  47.     @Override  
  48.     public void run() {  
  49.         //安全性检测   
  50.         String root=documentRootDirectory.getPath();  
  51.           
  52.         while (true) {  
  53.             Socket connection;  
  54.             synchronized (pool) {  
  55.                 while (pool.isEmpty()) {  
  56.                     try {  
  57.                         pool.wait();  
  58.                     } catch (InterruptedException e) {  
  59.                     }  
  60.                       
  61.                 }  
  62.                 connection=(Socket)pool.remove(0);  
  63.             }  
  64.               
  65.             try {  
  66.                 String fileName;  
  67.                 String contentType;  
  68.                 OutputStream raw=new BufferedOutputStream(connection.getOutputStream());  
  69.                 Writer out=new OutputStreamWriter(raw);  
  70.                 Reader in=new InputStreamReader(new BufferedInputStream(connection.getInputStream()), "ASCII");  
  71.                   
  72.                 StringBuffer request=new StringBuffer(80);  
  73.                 while (true) {  
  74.                     int c=in.read();  
  75.                     if (c=='\t'||c=='\n'||c==-1) {  
  76.                         break;  
  77.                     }  
  78.                     request.append((char)c);  
  79.                 }  
  80.                   
  81.                 String get=request.toString();  
  82.                 //记录日志   
  83.                 System.out.println(get);  
  84.                   
  85.                 StringTokenizer st=new StringTokenizer(get);  
  86.                 String method=st.nextToken();  
  87.                 String version="";  
  88.                 if (method=="GET") {  
  89.                     fileName=st.nextToken();  
  90.                     if (fileName.endsWith("/")) {  
  91.                         fileName+=indexFileName;  
  92.                     }  
  93.                     contentType=guessContentTypeFromName(fileName);  
  94.                     if (st.hasMoreTokens()) {  
  95.                         version=st.nextToken();  
  96.                     }  
  97.                       
  98.                     File theFile=new File(documentRootDirectory,fileName.substring(1,fileName.length()));  
  99.                     if (theFile.canRead()&&theFile.getCanonicalPath().startsWith(root)) {  
  100.                         DataInputStream fis=new DataInputStream(new BufferedInputStream(new FileInputStream(theFile)));  
  101.                         byte[] theData=new byte[(int)theFile.length()];  
  102.                         fis.readFully(theData);  
  103.                         fis.close();  
  104.                         if (version.startsWith("HTTP ")) {  
  105.                             out.write("HTTP/1.0 200 OK\r\n");  
  106.                             Date now=new Date();  
  107.                             out.write("Date: "+now+"\r\n");  
  108.                             out.write("Server: JHTTP 1.0\r\n");  
  109.                             out.write("Content-length: "+theData.length+"\r\n");  
  110.                             out.write("Content-Type: "+contentType+"\r\n\r\n");  
  111.                             out.flush();  
  112.                         }  
  113.                         raw.write(theData);  
  114.                         raw.flush();  
  115.                     }else {  
  116.                         if (version.startsWith("HTTP ")) {  
  117.                             out.write("HTTP/1.0 404 File Not Found\r\n");  
  118.                             Date now=new Date();  
  119.                             out.write("Date: "+now+"\r\n");  
  120.                             out.write("Server: JHTTP 1.0\r\n");  
  121.                             out.write("Content-Type: text/html\r\n\r\n");  
  122.                             out.flush();  
  123.                         }  
  124.                         out.write("<HTML>\r\n");  
  125.                         out.write("<HEAD><TITLE>File Not Found</TITLE></HRAD>\r\n");  
  126.                         out.write("<BODY>\r\n");  
  127.                         out.write("<H1>HTTP Error 404: File Not Found</H1>");  
  128.                         out.write("</BODY></HTML>\r\n");  
  129.                     }  
  130.                 }else {//方法不等于"GET"   
  131.                     if (version.startsWith("HTTP ")) {  
  132.                         out.write("HTTP/1.0 501 Not Implemented\r\n");  
  133.                         Date now=new Date();  
  134.                         out.write("Date: "+now+"\r\n");  
  135.                         out.write("Server: JHTTP 1.0\r\n");  
  136.                         out.write("Content-Type: text/html\r\n\r\n");  
  137.                         out.flush();  
  138.                     }  
  139.                     out.write("<HTML>\r\n");  
  140.                     out.write("<HEAD><TITLE>Not Implemented</TITLE></HRAD>\r\n");  
  141.                     out.write("<BODY>\r\n");  
  142.                     out.write("<H1>HTTP Error 501: Not Implemented</H1>");  
  143.                     out.write("</BODY></HTML>\r\n");  
  144.                 }  
  145.                   
  146.             } catch (IOException e) {  
  147.             }finally{  
  148.                 try {  
  149.                     connection.close();  
  150.                 } catch (IOException e2) {  
  151.                 }  
  152.                   
  153.             }  
  154.         }  
  155.     }  
  156.       
  157.     public static String guessContentTypeFromName(String name) {  
  158.         if (name.endsWith(".html")||name.endsWith(".htm")) {  
  159.             return "text/html";  
  160.         }else if (name.endsWith(".txt")||name.endsWith(".java")) {  
  161.             return "text/plain";  
  162.         }else if (name.endsWith(".gif")) {  
  163.             return "image/gif";  
  164.         }else if (name.endsWith(".class")) {  
  165.             return "application/octet-stream";  
  166.         }else if (name.endsWith(".jpg")||name.endsWith(".jpeg")) {  
  167.             return "image/jpeg";  
  168.         }else {  
  169.             return "text/plain";  
  170.         }  
  171.     }  
  172.   
  173. }  
不足与改善:

这个服务器可以提供一定的功能,但仍然十分简单,还可以添加以下的一些特性:

(1)       服务器管理界面

(2)       支持CGI程序和Java Servlet API

(3)       支持其他请求方法

(4)       常见Web日志文件格式的日志文件

(5)       支持多文档根目录,这样各用户可以有自己的网站

最后,花点时间考虑一下可以采用什么方法来优化此服务器。如果真的希望使用JHTTP运行高流量的网站,还可以做一些事情来加速此服务器。第一点也是最重要的一点就是使用即时编译器(JIT),如HotSpot。JIT可以将程序的性能提升大约一个数量级。第二件事就是实现智能缓存。记住接受的请求,将最频繁的请求文件的数据存储在Hashtable中,使之保存在内存中。使用低优先级的线程更新此缓存。

linux
相关资讯       Java教程  HTTP服务器 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款