自己动手写http服务器---java版

来源:互联网 发布:c类超高速usb 3.0端口 编辑:程序博客网 时间:2024/05/23 19:19

最简单的http服务器,可下载源码:http://download.csdn.net/detail/ajaxhu/6356885


大概介绍一下原理吧,浏览器打开网页可以简单分为3个阶段:

1.通过socket向服务器发送一个符合一定格式的请求字符串(里面包含了用户输入的网址),比如:

Accepttext/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8Accept-Encodinggzip, deflateAccept-Languagezh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3Connectionkeep-aliveHostlocalhost:8001User-AgentMozilla/5.0 (Windows NT 6.1; rv:22.0) Gecko/20100101 Firefox/22.0

2.服务器收到浏览器的请求字符串,解析出用户所请求的网址,网址其实对应服务器中的文件。
   例如 http:\\www.demo.com其实对应服务器里的 http:\\www.demo.com\index.html,服务器会将index.html这个文件读取到byte数组中,并加上头信息(也是字符串),返回给发送请求的浏览器。

3.浏览器接收到服务器返回的字节流,根据返回的头信息,判断返回的byte数组原始的数据类型(网页、图片、其他),例如返回的头信息如下:
  Content-Typetext/html
说明返回的byte数组原来是html页面,浏览器会解析html页面,显示数据。
如果服务器返回的头信息如下:
Content-Typeimage/jpeg说明返回的byte数组原来是图片,浏览器会将byte数组存储为图片,显示图片。

下面给出源码:
注:1.要运行程序,需要在同目录下新建webapp文件夹,将想运行的网站放入(暂时只支持html,jpg,gif,png)
2.程序运行参数:可以无参数运行,默认绑定80端口,有可能会冲突。可添加一个参数设定端口,例如:java -jar MyHtmlServer.jar 8001
8001为绑定的端口号。
3.运行程序后,在浏览器中输入 http://localhost:端口号/资源路径即可。例如绑定的是8001端口,在webapp文件夹下有index.html文件,现在需要访问这个文件,在浏览器中输入:http://localhost:8001/index.html 即可访问。如果绑定的是80端口,可直接写:http://localhost/index.html,浏览器默认使用80作为服务器端口。
源码:
[java] view plaincopy
  1. import java.io.BufferedReader;  
  2. import java.io.ByteArrayOutputStream;  
  3. import java.io.File;  
  4. import java.io.FileInputStream;  
  5. import java.io.IOException;  
  6. import java.io.InputStream;  
  7. import java.io.InputStreamReader;  
  8. import java.io.InterruptedIOException;  
  9. import java.io.OutputStream;  
  10. import java.net.ServerSocket;  
  11. import java.net.Socket;  
  12.   
  13. public class MyHtmlServer {  
  14.       
  15.     public static void main(String[] args) throws IOException {  
  16.         int port=80;  
  17.         if(args.length>0)  
  18.             port=Integer.valueOf(args[0]);  
  19.         new MyHtmlServer().start(port);  
  20.   
  21.     }  
  22.       
  23.     /** 
  24.      * 在指定端口启动http服务器 
  25.      * @param port 指定的端口 
  26.      * @throws IOException 
  27.      */  
  28.     public void start(int port) throws IOException {  
  29.         ServerSocket server = new ServerSocket(port);  
  30.         System.out.println("server start at "+port+"...........");  
  31.         while (true) {  
  32.             Socket client = server.accept();  
  33.             ServerThread serverthread = new ServerThread(client);  
  34.             serverthread.start();  
  35.   
  36.         }  
  37.     }  
  38.   
  39.     /** 
  40.      * 服务器响应线程,每收到一次浏览器的请求就会启动一个ServerThread线程 
  41.      * @author  
  42.      * 
  43.      */  
  44.     class ServerThread extends Thread {  
  45.         Socket client;  
  46.   
  47.         public ServerThread(Socket client) {  
  48.             this.client = client;  
  49.         }  
  50.           
  51.         /** 
  52.          * 读取文件内容,转化为byte数组 
  53.          * @param filename 文件名 
  54.          * @return 
  55.          * @throws IOException 
  56.          */  
  57.         public  byte[] getFileByte(String filename) throws IOException  
  58.         {  
  59.             ByteArrayOutputStream baos=new ByteArrayOutputStream();  
  60.             File file=new File(filename);  
  61.             FileInputStream fis=new FileInputStream(file);  
  62.             byte[] b=new byte[1000];  
  63.             int read;  
  64.             while((read=fis.read(b))!=-1)  
  65.             {  
  66.                 baos.write(b,0,read);  
  67.             }  
  68.             fis.close();  
  69.             baos.close();  
  70.             return baos.toByteArray();  
  71.         }  
  72.   
  73.           
  74.         /** 
  75.          * 分析http请求中的url,分析用户请求的资源,并将请求url规范化 
  76.          * 例如请求 "/"要规范成"/index.html","/index"要规范成"/index.html" 
  77.          * @param queryurl 用户原始的url 
  78.          * @return 规范化的url,即为用户请求资源的路径 
  79.          */  
  80.         private String getQueryResource(String queryurl)  
  81.         {  
  82.             String queryresource=null;  
  83.             int index=queryurl.indexOf('?');  
  84.             if(index!=-1)  
  85.             {  
  86.                 queryresource=queryurl.substring(0,queryurl.indexOf('?'));  
  87.             }  
  88.             else  
  89.                 queryresource=queryurl;  
  90.               
  91.             index=queryresource.lastIndexOf("/");  
  92.             if(index+1==queryresource.length())  
  93.             {  
  94.                 queryresource=queryresource+"index.html";  
  95.             }  
  96.             else  
  97.             {  
  98.                 String filename=queryresource.substring(index+1);  
  99.                 if(!filename.contains("."))  
  100.                     queryresource=queryresource+".html";  
  101.             }             
  102.             return queryresource;  
  103.   
  104.         }  
  105.           
  106.       
  107.         /** 
  108.          * 根据用户请求的资源类型,设定http响应头的信息,主要是判断用户请求的文件类型(html、jpg...) 
  109.          * @param queryresource 
  110.          * @return 
  111.          */  
  112.         private String getHead(String queryresource)  
  113.         {  
  114.             String filename="";  
  115.             int index=queryresource.lastIndexOf("/");  
  116.             filename=queryresource.substring(index+1);  
  117.             String[] filetypes=filename.split("\\.");  
  118.             String filetype=filetypes[filetypes.length-1];  
  119.             if(filetype.equals("html"))  
  120.             {  
  121.                 return "HTTP/1.0200OK\n"+"Content-Type:text/html\n" + "Server:myserver\n" + "\n";  
  122.             }  
  123.             else if(filetype.equals("jpg")||filetype.equals("gif")||filetype.equals("png"))  
  124.             {  
  125.                 return "HTTP/1.0200OK\n"+"Content-Type:image/jpeg\n" + "Server:myserver\n" + "\n";  
  126.             }  
  127.             else return null;  
  128.               
  129.         }  
  130.   
  131.         @Override  
  132.         public void run() {  
  133.             InputStream is;  
  134.             try {  
  135.                 is = client.getInputStream();  
  136.                 BufferedReader br = new BufferedReader(  
  137.                         new InputStreamReader(is));  
  138.                 int readint;  
  139.                 char c;  
  140.                 byte[] buf = new byte[1000];  
  141.                 OutputStream os = client.getOutputStream();  
  142.                 client.setSoTimeout(50);  
  143.                 byte[] data = null;  
  144.                 String cmd = "";  
  145.                 String queryurl = "";  
  146.                 int state = 0;  
  147.                 String queryresource;  
  148.                 String head;  
  149.                 while (true) {  
  150.                     readint = is.read();  
  151.                     c = (char) readint;  
  152.                     boolean space=Character.isWhitespace(readint);  
  153.                     switch (state) {  
  154.                     case 0:  
  155.                         if (space)  
  156.                             continue;  
  157.                         state = 1;  
  158.                     case 1:  
  159.                         if (space) {  
  160.                             state=2;  
  161.                             continue;  
  162.                         }  
  163.                         cmd+=c;  
  164.                         continue;  
  165.                     case 2:  
  166.                         if(space)  
  167.                             continue;  
  168.                         state=3;  
  169.                     case 3:  
  170.                         if(space)  
  171.                             break;  
  172.                         queryurl+=c;  
  173.                         continue;  
  174.                     }  
  175.                     break;  
  176.                 }  
  177.   
  178.                 queryresource=getQueryResource(queryurl);  
  179.                 head=getHead(queryresource);  
  180.   
  181.                 while (true) {  
  182.                     try {  
  183.                         if ((readint = is.read(buf)) > 0) {  
  184.                         //  System.out.write(buf);  
  185.                         } else if (readint < 0)  
  186.                             break;  
  187.                     } catch (InterruptedIOException e) {  
  188.                         data = getFileByte("webapp"+queryresource);  
  189.                     }  
  190.   
  191.                     if (data != null) {  
  192.                         os.write(head.getBytes("utf-8"));  
  193.                         os.write(data);  
  194.                         os.close();  
  195.                         break;  
  196.                     }  
  197.                 }  
  198.             } catch (IOException e) {  
  199.                 // TODO Auto-generated catch block  
  200.                 e.printStackTrace();  
  201.             }  
  202.   
  203.         }  
  204.     }  
  205.       
  206.       
  207.           
  208.       
  209.       
  210.       
  211.   
  212.       
  213. }  
0 0