一个简易的java http服务器

TTP是个大协议,完整功能的HTTP服务器必须响应资源请求,将URL转换为本地系统的资源名。响应各种形式的HTTP请求(GET、POST等)。处理不存在的文件请求,返回各种形式的状态码,解析MIME类型等。但许多特定功能的HTTP服务器并不需要所有这些功能。例如,很多网站只是想显示“建设中“的消息。很显然,Apache对于这样的网站是大材小用了。这样的网站完全可以使用只做一件事情的定制服务器。Java网络类库使得编写这样的单任务服务器轻而易举。

 

定制服务器不只是用于小网站。大流量的网站如Yahoo,也使用定制服务器,因为与一般用途的服务器相比,只做一件事情的服务器通常要快得多。针对某项任务来优化特殊用途的服务器很容易;其结果往往比需要响应很多种请求的一般用途服务器高效得多。例如,对于重复用于多页面或大流量页面中的图标和图片,用一个单独的服务器处理会更好(并且还可以避免在请求时携带不必要的Cookie,因而可以减少请求/响应数据,从而减少下载带宽,提升速度);这个服务器在启动时把所有图片文件读入内存,从RAM中直接提供这些文件,而不是每次请求都从磁盘上读取。此外,如果你不想在包含这些图片的页面请求之外单独记录这些图片,这个单独服务器则会避免在日志记录上浪费时间。

 

本篇为大家简要演示三种HTTP服务器:

(1)     简单的单文件服务器

(2)     重定向服务器

(3)     完整功能的HTTP服务器


简单的单文件服务器

该服务器的功能:无论接受到何种请求,都始终发送同一个文件。这个服务器命名为SingleFileHTTPServer,文件名、本地端口和内容编码方式从命令行读取。如果缺省端口,则假定端口号为80。如果缺省编码方式,则假定为ASCII。

[java]  view plain  copy
 print ?
  1. import java.io.*;  
  2. import java.net.ServerSocket;  
  3. import java.net.Socket;  
  4.   
  5.   
  6. public class SingleFileHTTPServer extends Thread {  
  7.       
  8.     private byte[] content;  
  9.     private byte[] header;  
  10.     private int port=80;  
  11.       
  12.     private SingleFileHTTPServer(String data, String encoding,  
  13.                 String MIMEType, int port) throws UnsupportedEncodingException {  
  14.         this(data.getBytes(encoding), encoding, MIMEType, port);  
  15.     }  
  16.       
  17.     public SingleFileHTTPServer(byte[] data, String encoding, String MIMEType, int port)throws UnsupportedEncodingException {  
  18.         this.content=data;  
  19.         this.port=port;  
  20.         String header="HTTP/1.0 200 OK\r\n"+  
  21.             "Server: OneFile 1.0\r\n"+  
  22.             "Content-length: "+this.content.length+"\r\n"+  
  23.             "Content-type: "+MIMEType+"\r\n\r\n";  
  24.         this.header=header.getBytes("ASCII");  
  25.     }  
  26.       
  27.     public void run() {  
  28.         try {  
  29.             ServerSocket server=new ServerSocket(this.port);  
  30.             System.out.println("Accepting connections on port "+server.getLocalPort());  
  31.             System.out.println("Data to be sent:");  
  32.             System.out.write(this.content);  
  33.               
  34.             while (true) {  
  35.                 Socket connection=null;  
  36.                 try {  
  37.                     connection=server.accept();  
  38.                     OutputStream out=new BufferedOutputStream(connection.getOutputStream());  
  39.                     InputStream in=new BufferedInputStream(connection.getInputStream());  
  40.                       
  41.                     StringBuffer request=new StringBuffer();  
  42.                     while (true) {  
  43.                         int c=in.read();  
  44.                         if (c=='\r'||c=='\n'||c==-1) {  
  45.                             break;  
  46.                         }  
  47.                         request.append((char)c);  
  48.                           
  49.                     }  
  50.                           
  51.                         //如果检测到是HTTP/1.0及以后的协议,按照规范,需要发送一个MIME首部  
  52.                         if (request.toString().indexOf("HTTP/")!=-1) {  
  53.                             out.write(this.header);  
  54.                         }  
  55.                           
  56.                         out.write(this.content);  
  57.                         out.flush();  
  58.                       
  59.                 } catch (IOException e) {  
  60.                     // TODO: handle exception  
  61.                 }finally{  
  62.                     if (connection!=null) {  
  63.                         connection.close();  
  64.                     }  
  65.                 }  
  66.             }  
  67.               
  68.         } catch (IOException e) {  
  69.             System.err.println("Could not start server. Port Occupied");  
  70.         }  
  71.     }  
  72.       
  73.     public static void main(String[] args) {  
  74.         try {  
  75.             String contentType="text/plain";  
  76.             if (args[0].endsWith(".html")||args[0].endsWith(".htm")) {  
  77.                 contentType="text/html";  
  78.             }  
  79.               
  80.             InputStream in=new FileInputStream(args[0]);  
  81.             ByteArrayOutputStream out=new ByteArrayOutputStream();  
  82.             int b;  
  83.             while ((b=in.read())!=-1) {  
  84.                 out.write(b);  
  85.             }  
  86.             byte[] data=out.toByteArray();  
  87.               
  88.             //设置监听端口  
  89.             int port;  
  90.             try {  
  91.                 port=Integer.parseInt(args[1]);  
  92.                 if (port<1||port>65535) {  
  93.                     port=80;  
  94.                 }  
  95.             } catch (Exception e) {  
  96.                 port=80;  
  97.             }  
  98.               
  99.             String encoding="ASCII";  
  100.             if (args.length>2) {  
  101.                 encoding=args[2];  
  102.             }  
  103.               
  104.             Thread t=new SingleFileHTTPServer(data, encoding, contentType, port);  
  105.             t.start();  
  106.               
  107.         } catch (ArrayIndexOutOfBoundsException e) {  
  108.              System.out.println("Usage:java SingleFileHTTPServer filename port encoding");  
  109.         }catch (Exception e) {  
  110.             System.err.println(e);// TODO: handle exception  
  111.         }  
  112.     }  
  113. }  

SingleFileHTTPServer类本身是Thread的子类。它的run()方法处理入站连接。此服务器可能只是提供小文件,而且只支持低吞吐量的web网站。由于服务器对每个连接所需完成的所有工作就是检查客户端是否支持HTTP/1.0,并为连接生成一两个较小的字节数组,因此这可能已经足够了。另一方面,如果你发现客户端被拒绝,则可以使用多线程。许多事情取决于所提供文件的大小,每分钟所期望连接的峰值数和主机上Java的线程模型。对弈这个程序复杂写的服务器,使用多线程将会有明显的收益。

Run()方法在指定端口创建一个ServerSocket。然后它进入无限循环,不断地接受连接并处理连接。当接受一个socket时,就会由一个InputStream从客户端读取请求。它查看第一行是否包含字符串HTTP。如果包含此字符串,服务器就假定客户端理解HTTP/1.0或以后的版本,因此为该文件发送一个MIME首部;然后发送数据。如果客户端请求不包含字符串HTTP,服务器就忽略首部,直接发送数据。最后服务器关闭连接,尝试接受下一个连接。

而main()方法只是从命令行读取参数。从第一个命令行参数读取要提供的文件名。如果没有指定文件或者文件无法打开,就显示一条错误信息,程序退出。如果文件能够读取,其内容就读入byte数组data.关于文件的内容类型,将进行合理的猜测,结果存储在contentType变量中。接下来,从第二个命令行参数读取端口号。如果没有指定端口或第二个参数不是0到65535之间的整数,就使用端口80。从第三个命令行参数读取编码方式(前提是提供了)。否则,编码方式就假定为ASCII。然后使用这些值构造一个SingleFileHTTPServer对象,开始运行。这是唯一可能的接口。

下面是测试的结果:

命令行编译代码并设置参数:


telnet::

首先,启用telnet服务(如果不会,自行google之),接着测试该主机的端口:


结果(可以看到请求的输出内容):



HTTP协议测试:


文档(这是之前一篇文章--小车动画的文档):


重定向服务器

实现的功能——将用户从一个Web网站重定向到另一个站点。下例从命令行读取URL和端口号,打开此端口号的服务器可能速度会很快,因此不需要多线程。尽管日次,使用多线程可能还是会带来一些好处,尤其是对于网络带宽很低、吞吐量很小的网站。在此主要是为了演示,所以,已经将该服务器做成多线程的了。这里为了简单起见,为每个连接都启用了一个线程,而不是采用线程池。或许更便于理解,但这真的有些浪费系统资源并且显得低效。

[java]  view plain  copy
 print ?
  1. import java.io.BufferedInputStream;  
  2. import java.io.BufferedWriter;  
  3. import java.io.IOException;  
  4. import java.io.InputStreamReader;  
  5. import java.io.OutputStreamWriter;  
  6. import java.io.Reader;  
  7. import java.io.Writer;  
  8. import java.net.BindException;  
  9. import java.net.ServerSocket;  
  10. import java.net.Socket;  
  11. import java.util.Date;  
  12.   
  13.   
  14. public class Redirector implements Runnable {  
  15.   
  16.     private int port;  
  17.     private String newSite;  
  18.       
  19.     public Redirector(String site, int port){  
  20.         this.port=port;  
  21.         this.newSite=site;  
  22.     }  
  23.       
  24.     @Override  
  25.     public void run() {  
  26.         try {  
  27.             ServerSocket server=new ServerSocket(port);  
  28.             System.out.println("Redirecting connection on port"  
  29.                     +server.getLocalPort()+" to "+newSite);  
  30.               
  31.             while (true) {  
  32.                 try {  
  33.                     Socket socket=server.accept();  
  34.                     Thread thread=new RedirectThread(socket);  
  35.                     thread.start();  
  36.                 } catch (IOException e) {  
  37.                     // TODO: handle exception  
  38.                 }  
  39.             }  
  40.         } catch (BindException e) {  
  41.             System.err.println("Could not start server. Port Occupied");  
  42.         }catch (IOException e) {  
  43.             System.err.println(e);  
  44.         }  
  45.           
  46.     }  
  47.       
  48.     class RedirectThread extends Thread {  
  49.   
  50.         private Socket connection;  
  51.           
  52.         RedirectThread(Socket s) {  
  53.             this.connection=s;  
  54.         }  
  55.           
  56.         public void run() {  
  57.             try {  
  58.                 Writer out=new BufferedWriter(  
  59.                         new OutputStreamWriter(connection.getOutputStream(),"ASCII"));  
  60.                 Reader in=new InputStreamReader(  
  61.                         new BufferedInputStream(connection.getInputStream()));  
  62.                   
  63.                 StringBuffer request=new StringBuffer(80);  
  64.                 while (true) {  
  65.                     int c=in.read();  
  66.                     if (c=='\t'||c=='\n'||c==-1) {  
  67.                         break;  
  68.                     }  
  69.                     request.append((char)c);  
  70.                 }  
  71.                   
  72.                 String get=request.toString();  
  73.                 int firstSpace=get.indexOf(' ');  
  74.                 int secondSpace=get.indexOf(' ', firstSpace+1);  
  75.                 String theFile=get.substring(firstSpace+1, secondSpace);  
  76.                   
  77.                 if (get.indexOf("HTTP")!=-1) {  
  78.                     out.write("HTTP/1.0 302 FOUND\r\n");  
  79.                     Date now=new Date();  
  80.                     out.write("Date: "+now+"\r\n");  
  81.                     out.write("Server: Redirector 1.0\r\n");  
  82.                     out.write("Location: "+newSite+theFile+"\r\n");  
  83.                     out.write("Content-Type: text/html\r\n\r\n");  
  84.                     out.flush();  
  85.                 }  
  86.                   
  87.                 //并非所有的浏览器都支持重定向,  
  88.                 //所以我们需要生成一个适用于所有浏览器的HTML文件,来描述这一行为  
  89.                 out.write("<HTML><HEAD><TITLE>Document moved</TITLE></HEAD>\r\n");  
  90.                 out.write("<BODY><H1>Document moved</H1></BODY>\r\n");  
  91.                 out.write("The document "+theFile  
  92.                         +" has moved to \r\n<A HREF=\""+newSite+theFile+"\">"  
  93.                         +newSite+theFile  
  94.                         +"</A>.\r\n Please update your bookmarks");  
  95.                 out.write("</BODY></HTML>\r\n");  
  96.                 out.flush();  
  97.                 } catch (IOException e) {  
  98.             }finally{  
  99.                 try {  
  100.                     if (connection!=null) {  
  101.                         connection.close();  
  102.                     }  
  103.                 } catch (IOException e2) {  
  104.                       
  105.                 }  
  106.             }  
  107.         }  
  108.           
  109.     }  
  110.       
  111.     /** 
  112.      * @param args 
  113.      */  
  114.     public static void main(String[] args) {  
  115.         int thePort;  
  116.         String theSite;  
  117.           
  118.         try {  
  119.             theSite=args[0];  
  120.               
  121.             //如果结尾有'/',则去除  
  122.             if (theSite.endsWith("/")) {  
  123.                 theSite=theSite.substring(0,theSite.length()-1);  
  124.             }  
  125.         } catch (Exception e) {  
  126.             System.out.println("Usage: java Redirector http://www.newsite.com/ port");  
  127.             return;  
  128.         }  
  129.           
  130.         try {  
  131.             thePort=Integer.parseInt(args[1]);  
  132.         } catch (Exception e) {  
  133.             thePort=80;  
  134.         }  
  135.           
  136.         Thread t=new Thread(new Redirector(theSite, thePort));  
  137.         t.start();  
  138.   
  139.     }  
  140.       
  141. }  

HTTP测试:

侦听8010端口,此处重定向到百度:




main()方法提供一个非常简单的界面,读取新网站的URL(为了把链接重定向到该URL)和监听本地端口。它使用这些信息构造了一个Rredirector对象。然后它使用所生成的Runnable对象(Redirector实现了Runnable)来生成一个新线程并启动。如果没有指定端口,Rredirector则会监听80端口。

Redirectro的run()方法将服务器socket绑定与此端口,显示一个简短的状态消息,然后进入无限循环,监听连接。每次接受连接,返回的Socket对象会用来构造一个RedirectThread。然后这个RedirectThread被启动。所有与客户端进一步的交互由此新线程完成。Redirector的run()方法只是等待下一个入站连接。

RedirectThread的run()方法完成了很多工作。它先把一个Writer链接到Socket的输出流,把一个Reader链接到Socket的输入流。输入流和输出流都有缓冲。然后run()方法读取客户端发送的第一行。虽然客户端可能会发送整个Mime首部,但我们会忽略这些。第一行包含所有所需的信息。这一行内容可能会是这样:

GET /directory/filename.html HTTP/1.0

可能第一个词是POST或PUT,也可能没有HTTP版本。

返回的输出,第一行显示为:

HTTP/1.0 302 FOUND

这是一个HTTP/1.0响应吗,告知客户端要被重定向。第二行是“Date:”首部,给出服务器的当前时间。这一行是可选的。第三行是服务器的名和版本;这一行也是可选的,但蜘蛛程序可用它来统计记录最流行的web服务器。下一行是“Location:”首部,对于此服务器这是必须的。它告知客户端要重定向的位置。最后是标准的“Content-type:”首部。这里发送内容类型text/html,只是客户端将会看到的HTML。最后,发送一个空行来标识首部数据的结束。

如果浏览器不支持重定向,那么那段HTML标签就会被发送。


功能完整的HTTP服务器

这里,我们来开发一个具有完整功能的HTTP服务器,成为JHTTP,它可以提供一个完整的文档树,包括图片、applet、HTML文件、文本文件等等。它与SingleFileHTTPServer非常相似,只不过它所关注的是GET请求。此服务器仍然是相当轻量级的;看过这个代码后,我们将讨论可能希望添加的其他特性。

由于这个服务器必须为可能很慢的网络连接提供文件系统的大文件,因此要改变其方式。这里不再在执行主线程中处理到达的每个请求,而是将入站连接放入池中。由一个RequestProcessor类实例从池中移走连接并进行处理。

[java]  view plain  copy
 print ?
  1. import java.io.File;  
  2. import java.io.IOException;  
  3. import java.net.ServerSocket;  
  4. import java.net.Socket;  
  5.   
  6. import org.omg.CORBA.Request;  
  7.   
  8.   
  9. public class JHTTP extends Thread {  
  10.   
  11.     private File documentRootDirectory;  
  12.     private String indexFileName="index.html";  
  13.     private ServerSocket server;  
  14.     private int numThreads=50;  
  15.       
  16.     public JHTTP(File documentRootDirectory,int port , String indexFileName)throws IOException {  
  17.         if (!documentRootDirectory.isDirectory()) {  
  18.             throw new IOException(documentRootDirectory+" does not exist as a directory ");  
  19.         }  
  20.         this.documentRootDirectory=documentRootDirectory;  
  21.         this.indexFileName=indexFileName;  
  22.         this.server=new ServerSocket(port);  
  23.     }  
  24.       
  25.     private JHTTP(File documentRootDirectory, int port)throws IOException {  
  26.         this(documentRootDirectory, port, "index.html");  
  27.     }  
  28.       
  29.     public void run(){  
  30.         for (int i = 0; i < numThreads; i++) {  
  31.             Thread t=new Thread(new RequestProcessor(documentRootDirectory, indexFileName));  
  32.             t.start();  
  33.         }  
  34.           
  35.         System.out.println("Accepting connection on port "  
  36.                 +server.getLocalPort());  
  37.         System.out.println("Document Root: "+documentRootDirectory);  
  38.         while (true) {  
  39.             try {  
  40.                 Socket request=server.accept();  
  41.                 RequestProcessor.processRequest(request);  
  42.             } catch (IOException e) {  
  43.                 // TODO: handle exception  
  44.             }  
  45.         }  
  46.     }  
  47.       
  48.       
  49.     /** 
  50.      * @param args 
  51.      */  
  52.     public static void main(String[] args) {  
  53.         File docroot;  
  54.         try {  
  55.             docroot=new File(args[0]);  
  56.         } catch (ArrayIndexOutOfBoundsException e) {  
  57.             System.out.println("Usage: java JHTTP docroot port indexfile");  
  58.             return;  
  59.         }  
  60.           
  61.         int port;  
  62.         try {  
  63.             port=Integer.parseInt(args[1]);  
  64.             if (port<0||port>65535) {  
  65.                 port=80;  
  66.             }  
  67.         } catch (Exception e) {  
  68.             port=80;  
  69.         }  
  70.           
  71.         try {  
  72.             JHTTP webserver=new JHTTP(docroot, port);  
  73.             webserver.start();  
  74.         } catch (IOException e) {  
  75.             System.out.println("Server could not start because of an "+e.getClass());  
  76.             System.out.println(e);  
  77.         }  
  78.           
  79.     }  
  80.   
  81. }  

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

[java]  view plain  copy
 print ?
  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中,使之保存在内存中。使用低优先级的线程更新此缓存。

——参考自网络编程

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值