JAVA实现HTTP服务器端

用java socket实现了一个简单的http服务器, 可以处理GET, POST,以及带一个附件的multipart类型的POST。虽然中途遇到了很多问题, 不过通过在论坛和几个高手交流了一下,问题都解决了。如果你觉得程序有些地方看不明白,可以参看这个帖子:http://topic.csdn.net/u/20090625/22/59a5bfc8-a6b6-445d-9829-ea6d462a4fe6.html .

虽然解析http头不是很规范,本来应该用原始的字节流, 我采用了一个折衷的方案,用DataInputStream.

本代码的实用性==0,但是可以帮助很好地了解http协议,然后其他的应用层协议大都如此。

如果你从来都没有了解过http协议,建议先搜索阅读一下,或者你还可以用下面的代码来简单的看一看到底浏览器和服务器之间都相互发送了什么数据。

MyHttpClient.java: 模拟浏览器的行为, 向服务器发送get/post请求,然后打印出服务器返回的消息。这样就可以查看当一个请求到来之后, 服务器到底都给浏览器发送了哪些消息。

[java]  view plain copy
  1. package socket;  
  2.   
  3. import java.io.*;  
  4. import java.net.*;  
  5.   
  6. public class MyHttpClient {  
  7.     public static void main(String[] args) throws Exception{  
  8.         InetAddress inet = InetAddress.getByName("www.baidu.com");  
  9.         System.out.println(inet.getHostAddress());  
  10.         Socket socket = new Socket(inet.getHostAddress(),80);  
  11.         InputStream in = socket.getInputStream();  
  12.         OutputStream out = socket.getOutputStream();  
  13.         BufferedReader reader = new BufferedReader(new InputStreamReader(in));  
  14.         PrintWriter writer = new PrintWriter(out);  
  15.         writer.println("GET /home.html HTTP/1.1");//home.html是关于百度的页面  
  16.         writer.println("Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/xaml+xml, application/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, application/msword, application/vnd.ms-excel, application/vnd.ms-powerpoint, */*");  
  17.         writer.println("Accept-Language: en-us,zh-cn;q=0.5");  
  18.         writer.println("Accept-Encoding: gzip, deflate");  
  19.         writer.println("Host: www.baidu.com");  
  20.         writer.println("User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)");  
  21.         writer.println("Connection: Keep-Alive");  
  22.         writer.println();  
  23.         writer.flush();  
  24.         String line = reader.readLine();  
  25.         while(line!=null){  
  26.             System.out.println(line);  
  27.             line = reader.readLine();  
  28.         }  
  29.         reader.close();  
  30.         writer.close();  
  31.     }  
  32. }  

MyServer.java: 模拟server端接收浏览器的请求,然后把整个请求的报文打印出来。程序运行之后直接用浏览器测试。

[java]  view plain copy
  1. package socket;  
  2.   
  3. import java.io.*;  
  4. import java.net.*;  
  5.   
  6. public class MyServer {  
  7.     public static void main(String[] args) throws IOException{  
  8.         ServerSocket svrSocket = new ServerSocket(8080);  
  9.         while(true){  
  10.             Socket socket = svrSocket.accept();  
  11.             //足够大的一个缓冲区  
  12.             byte[] buf = new byte[1024*1024];  
  13.             InputStream in = socket.getInputStream();  
  14.             int byteRead = in.read(buf, 01024*1024);  
  15.             String dataString = new String(buf, 0, byteRead);  
  16.             System.out.println(dataString);  
  17.             in.close();  
  18.             socket.close();  
  19.         }  
  20.     }  
  21. }  

主程序MyHttpServer.

[java]  view plain copy
  1. package socket;  
  2.   
  3. import java.io.*;  
  4. import java.net.*;  
  5. /** 
  6.  * MyHttpServer 实现一个简单的HTTP服务器端,可以获取用户提交的内容 
  7.  * 并给用户一个response 
  8.  * 因为时间的关系,对http头的处理显得不规范 
  9.  * 对于上传附件,暂时只能解析只上传一个附件而且附件位置在第一个的情况 
  10.  * 转载请注明来自http://blog.csdn.net/sunxing007 
  11.  * **/  
  12. public class MyHttpServer {  
  13.     //服务器根目录,post.html, upload.html都放在该位置  
  14.     public static String WEB_ROOT = "c:/root";  
  15.     //端口  
  16.     private int port;  
  17.     //用户请求的文件的url  
  18.     private String requestPath;  
  19.     //mltipart/form-data方式提交post的分隔符,   
  20.     private String boundary = null;  
  21.     //post提交请求的正文的长度  
  22.     private int contentLength = 0;  
  23.   
  24.     public MyHttpServer(String root, int port) {  
  25.         WEB_ROOT = root;  
  26.         this.port = port;  
  27.         requestPath = null;  
  28.     }  
  29.     //处理GET请求  
  30.     private void doGet(DataInputStream reader, OutputStream out) throws Exception {  
  31.         if (new File(WEB_ROOT + this.requestPath).exists()) {  
  32.             //从服务器根目录下找到用户请求的文件并发送回浏览器  
  33.             InputStream fileIn = new FileInputStream(WEB_ROOT + this.requestPath);  
  34.             byte[] buf = new byte[fileIn.available()];  
  35.             fileIn.read(buf);  
  36.             out.write(buf);  
  37.             out.close();  
  38.             fileIn.close();  
  39.             reader.close();  
  40.             System.out.println("request complete.");  
  41.         }  
  42.     }  
  43.     //处理post请求  
  44.     private void doPost(DataInputStream reader, OutputStream out) throws Exception {  
  45.         String line = reader.readLine();  
  46.         while (line != null) {  
  47.             System.out.println(line);  
  48.             line = reader.readLine();  
  49.             if ("".equals(line)) {  
  50.                 break;  
  51.             } else if (line.indexOf("Content-Length") != -1) {  
  52.                 this.contentLength = Integer.parseInt(line.substring(line.indexOf("Content-Length") + 16));  
  53.             }  
  54.             //表明要上传附件, 跳转到doMultiPart方法。  
  55.             else if(line.indexOf("multipart/form-data")!= -1){  
  56.                 //得multiltipart的分隔符  
  57.                 this.boundary = line.substring(line.indexOf("boundary") + 9);  
  58.                 this.doMultiPart(reader, out);  
  59.                 return;  
  60.             }  
  61.         }  
  62.         //继续读取普通post(没有附件)提交的数据  
  63.         System.out.println("begin reading posted data......");  
  64.         String dataLine = null;  
  65.         //用户发送的post数据正文  
  66.         byte[] buf = {};  
  67.         int size = 0;  
  68.         if (this.contentLength != 0) {  
  69.             buf = new byte[this.contentLength];  
  70.             while(size<this.contentLength){  
  71.                 int c = reader.read();  
  72.                 buf[size++] = (byte)c;  
  73.                   
  74.             }  
  75.             System.out.println("The data user posted: " + new String(buf, 0, size));  
  76.         }  
  77.         //发送回浏览器的内容  
  78.         String response = "";  
  79.         response += "HTTP/1.1 200 OK/n";  
  80.         response += "Server: Sunpache 1.0/n";  
  81.         response += "Content-Type: text/html/n";  
  82.         response += "Last-Modified: Mon, 11 Jan 1998 13:23:42 GMT/n";  
  83.         response += "Accept-ranges: bytes";  
  84.         response += "/n";  
  85.         String body = "<html><head><title>test server</title></head><body><p>post ok:</p>" + new String(buf, 0, size) + "</body></html>";  
  86.         System.out.println(body);  
  87.         out.write(response.getBytes());  
  88.         out.write(body.getBytes());  
  89.         out.flush();  
  90.         reader.close();  
  91.         out.close();  
  92.         System.out.println("request complete.");  
  93.     }  
  94.     //处理附件  
  95.     private void doMultiPart(DataInputStream reader, OutputStream out) throws Exception {  
  96.         System.out.println("doMultiPart ......");  
  97.         String line = reader.readLine();  
  98.         while (line != null) {  
  99.             System.out.println(line);  
  100.             line = reader.readLine();  
  101.             if ("".equals(line)) {  
  102.                 break;  
  103.             } else if (line.indexOf("Content-Length") != -1) {  
  104.                 this.contentLength = Integer.parseInt(line.substring(line.indexOf("Content-Length") + 16));  
  105.                 System.out.println("contentLength: " + this.contentLength);  
  106.             } else if (line.indexOf("boundary") != -1) {  
  107.                 //获取multipart分隔符  
  108.                 this.boundary = line.substring(line.indexOf("boundary") + 9);  
  109.             }  
  110.         }  
  111.         System.out.println("begin get data......");  
  112.         /*下面的注释是一个浏览器发送带附件的请求的全文,所有中文都是说明性的文字***** 
  113.         <HTTP头部内容略> 
  114.         ............ 
  115.         Cache-Control: no-cache 
  116.         <这里有一个空行,表明接下来的内容都是要提交的正文> 
  117.         -----------------------------7d925134501f6<这是multipart分隔符> 
  118.         Content-Disposition: form-data; name="myfile"; filename="mywork.doc" 
  119.         Content-Type: text/plain 
  120.          
  121.         <附件正文>........................................ 
  122.         ................................................. 
  123.          
  124.         -----------------------------7d925134501f6<这是multipart分隔符> 
  125.         Content-Disposition: form-data; name="myname"<其他字段或附件> 
  126.         <这里有一个空行> 
  127.         <其他字段或附件的内容> 
  128.         -----------------------------7d925134501f6--<这是multipart分隔符,最后一个分隔符多两个-> 
  129.         ****************************************************************/  
  130.         /** 
  131.          * 上面的注释是一个带附件的multipart类型的POST的全文模型, 
  132.          * 要把附件去出来,就是要找到附件正文的起始位置和结束位置 
  133.          * **/  
  134.         if (this.contentLength != 0) {  
  135.             //把所有的提交的正文,包括附件和其他字段都先读到buf.  
  136.             byte[] buf = new byte[this.contentLength];  
  137.             int totalRead = 0;  
  138.             int size = 0;  
  139.             while (totalRead < this.contentLength) {  
  140.                 size = reader.read(buf, totalRead, this.contentLength - totalRead);  
  141.                 totalRead += size;  
  142.             }  
  143.             //用buf构造一个字符串,可以用字符串方便的计算出附件所在的位置  
  144.             String dataString = new String(buf, 0, totalRead);  
  145.             System.out.println("the data user posted:/n" + dataString);  
  146.             int pos = dataString.indexOf(boundary);  
  147.             //以下略过4行就是第一个附件的位置  
  148.             pos = dataString.indexOf("/n", pos) + 1;  
  149.             pos = dataString.indexOf("/n", pos) + 1;  
  150.             pos = dataString.indexOf("/n", pos) + 1;  
  151.             pos = dataString.indexOf("/n", pos) + 1;  
  152.             //附件开始位置  
  153.             int start = dataString.substring(0, pos).getBytes().length;  
  154.             pos = dataString.indexOf(boundary, pos) - 4;  
  155.             //附件结束位置  
  156.             int end = dataString.substring(0, pos).getBytes().length;  
  157.             //以下找出filename  
  158.             int fileNameBegin = dataString.indexOf("filename") + 10;  
  159.             int fileNameEnd = dataString.indexOf("/n", fileNameBegin);  
  160.             String fileName = dataString.substring(fileNameBegin, fileNameEnd);  
  161.             /** 
  162.              * 有时候上传的文件显示完整的文件名路径,比如c:/my file/somedir/project.doc 
  163.              * 但有时候只显示文件的名字,比如myphoto.jpg. 
  164.              * 所以需要做一个判断。 
  165.             */  
  166.             if(fileName.lastIndexOf("//")!=-1){  
  167.                 fileName = fileName.substring(fileName.lastIndexOf("//") + 1);  
  168.             }  
  169.             fileName = fileName.substring(0, fileName.length()-2);  
  170.             OutputStream fileOut = new FileOutputStream("c://" + fileName);  
  171.             fileOut.write(buf, start, end-start);  
  172.             fileOut.close();  
  173.             fileOut.close();  
  174.         }  
  175.         String response = "";  
  176.         response += "HTTP/1.1 200 OK/n";  
  177.         response += "Server: Sunpache 1.0/n";  
  178.         response += "Content-Type: text/html/n";  
  179.         response += "Last-Modified: Mon, 11 Jan 1998 13:23:42 GMT/n";  
  180.         response += "Accept-ranges: bytes";  
  181.         response += "/n";  
  182.         out.write("<html><head><title>test server</title></head><body><p>Post is ok</p></body></html>".getBytes());  
  183.         out.flush();  
  184.         reader.close();  
  185.         System.out.println("request complete.");  
  186.     }  
  187.   
  188.     public void service() throws Exception {  
  189.         ServerSocket serverSocket = new ServerSocket(this.port);  
  190.         System.out.println("server is ok.");  
  191.         //开启serverSocket等待用户请求到来,然后根据请求的类别作处理  
  192.         //在这里我只针对GET和POST作了处理  
  193.         //其中POST具有解析单个附件的能力  
  194.         while (true) {  
  195.             Socket socket = serverSocket.accept();  
  196.             System.out.println("new request coming.");  
  197.             DataInputStream reader = new DataInputStream((socket.getInputStream()));  
  198.             String line = reader.readLine();  
  199.             String method = line.substring(04).trim();  
  200.             OutputStream out = socket.getOutputStream();  
  201.             this.requestPath = line.split(" ")[1];  
  202.             System.out.println(method);  
  203.             if ("GET".equalsIgnoreCase(method)) {  
  204.                 System.out.println("do get......");  
  205.                 this.doGet(reader, out);  
  206.             } else if ("POST".equalsIgnoreCase(method)) {  
  207.                 System.out.println("do post......");  
  208.                 this.doPost(reader, out);  
  209.             }  
  210.             socket.close();  
  211.             System.out.println("socket closed.");  
  212.         }  
  213.     }  
  214.     public static void main(String args[]) throws Exception {  
  215.         MyHttpServer server = new MyHttpServer("c:/root"8080);  
  216.         server.service();  
  217.     }  
  218. }  

测试文件post.html, upload.html都放在上面程序定义的WEB_ROOT下面。

post.html:处理普通的post请求

[xhtml]  view plain copy
  1. <html>   
  2. <head>   
  3. <title>test my server</title>   
  4. <meta http-equiv="Content-Type" content="text/html; charset=utf-8">   
  5. </head>   
  6. <body>   
  7. <p>upload</p>   
  8. 来自http://blog.csdn.net/sunxing007<br>  
  9. <form name="UploadForm" method="post" action="http://localhost:8080/">  
  10. <input type="text" name="myname" /><br>  
  11. <select name="myage">  
  12.   <option value="18">18</option>  
  13.   <option value="20">20</option>  
  14.   <option value="22">22</option>  
  15. </select><br>  
  16. <input type="submit"value="Sutmit">  
  17. </form>  
  18. </body>   
  19. </html>  

upload.html:测试带附件的post请求

[xhtml]  view plain copy
  1. <head>  
  2. <title>my page</title>  
  3. <style>  
  4.   table{  
  5.     border-collapse: collapse;  
  6.   }  
  7. </style>  
  8. </head>  
  9. <body>  
  10. 来自http://blog.csdn.net/sunxing007<br>  
  11.     <form action='http://localhost:8080/' method='post' enctype='multipart/form-data'>  
  12.     file: <input type='file' name='myfile' /><br>  
  13.     <input type='submit' />  
  14.     </form>  
  15. </body>  
  16. </html>  

一切准备妥当,并且MyHttpServer运行之后, 在浏览器输入http://localhost:8080/post.html和http://localhost:8080/upload.html即可进行测试.

转载请注明来自http://blog.csdn.net/sunxing007

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值