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

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

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

重定向服务器

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

  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端口。

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

       

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