实现HTTP服务器的三种方法

来源:互联网 发布:100教育网络辅导 编辑:程序博客网 时间:2024/05/18 04:08

1、使用socket简单实现http协议:

//参考链接:http://blog.csdn.net/sunxing007/article/details/4305956

[java] view plain copy
  1. import java.io.*;  
  2. import java.net.*;  
  3. /** 
  4.  * MyHttpServer 实现一个简单的HTTP服务器端,可以获取用户提交的内容 
  5.  * 并给用户一个response 
  6.  * 因为时间的关系,对http头的处理显得不规范 
  7.  * 对于上传附件,暂时只能解析只上传一个附件而且附件位置在第一个的情况 
  8.  * 转载请注明来自http://blog.csdn.net/sunxing007 
  9.  *  
  10.  * http://blog.csdn.net/sunxing007/article/details/4305956 
  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.             try {  
  196.                 Socket socket = serverSocket.accept();  
  197.                 System.out.println("new request coming.");  
  198.                 DataInputStream reader = new DataInputStream((socket.getInputStream()));  
  199.                 String line = reader.readLine();  
  200.                 if(line!=null){  
  201.                       
  202.                      String method = line.substring(04).trim();  
  203.                      OutputStream out = socket.getOutputStream();  
  204.                      this.requestPath = line.split(" ")[1];  
  205.                      System.out.println(method);  
  206.                      if ("GET".equalsIgnoreCase(method)) {  
  207.                          System.out.println("do get......");  
  208.                          this.doGet(reader, out);  
  209.                      } else if ("POST".equalsIgnoreCase(method)) {  
  210.                          System.out.println("do post......");  
  211.                          this.doPost(reader, out);  
  212.                      }  
  213.                       
  214.                 }else{  
  215.                     System.err.println("line is null!");  
  216.                 }  
  217.                 socket.close();  
  218.                 System.out.println("socket closed.");  
  219.             } catch (Exception e) {  
  220.                 e.printStackTrace();  
  221.             }  
  222.              
  223.         }  
  224.     }  
  225.     public static void main(String args[]) throws Exception {  
  226.         MyHttpServer server = new MyHttpServer("c:/root"8080);  
  227.         server.service();  
  228.     }  
  229. }  

2、使用jdk自导的httpserver组件

[java] view plain copy
  1. import java.io.IOException;  
  2. import java.io.OutputStream;  
  3. import java.net.InetSocketAddress;  
  4. import java.util.Iterator;  
  5. import java.util.List;  
  6. import java.util.Set;  
  7. import java.util.concurrent.Executors;  
  8.   
  9. import com.sun.net.httpserver.Headers;  
  10. import com.sun.net.httpserver.HttpExchange;  
  11. import com.sun.net.httpserver.HttpHandler;  
  12. import com.sun.net.httpserver.HttpServer;  
  13. //在eclipse中会出现Access restriction: The type Headers is not accessible due to restriction on required library  
  14. //解决办法:把Windows-Preferences-Java-Complicer- Errors/Warnings里面的Deprecated and restricted API中的Forbidden references(access rules)选为Warning就可以编译通过。  
  15. /** 
  16.  * 使用jdk自带sun httpserver组件构建Http服务器, 
  17.  * JDK自带的HttpServer是一个非常轻量级的Http服务端框架,但是它非常灵活,易于扩展, 
  18.  * @author Administrator 
  19.  * 
  20.  */  
  21. public class HttpServerDemo {  
  22.     public static void main(String[] args) throws IOException {  
  23.         InetSocketAddress addr = new InetSocketAddress(8080);  
  24.         HttpServer server = HttpServer.create(addr, 0);  
  25.   
  26.         server.createContext("/"new MyHandler());  
  27.         server.setExecutor(Executors.newCachedThreadPool());  
  28.         server.start();  
  29.         System.out.println("Server is listening on port 8080");  
  30.     }  
  31. }  
  32.   
  33. class MyHandler implements HttpHandler {  
  34.       
  35.     public void handle(HttpExchange exchange) throws IOException {  
  36.           
  37.         String requestMethod = exchange.getRequestMethod();  
  38.         System.out.println("处理新请求:"+requestMethod);  
  39.         if (requestMethod.equalsIgnoreCase("GET")) {  
  40.             Headers responseHeaders = exchange.getResponseHeaders();  
  41.             responseHeaders.set("Content-Type""text/plain");  
  42.             exchange.sendResponseHeaders(2000);  
  43.   
  44.             OutputStream responseBody = exchange.getResponseBody();  
  45.             Headers requestHeaders = exchange.getRequestHeaders();  
  46.             Set<String> keySet = requestHeaders.keySet();  
  47.             Iterator<String> iter = keySet.iterator();  
  48.             while (iter.hasNext()) {  
  49.                 String key = iter.next();  
  50.                 List values = requestHeaders.get(key);  
  51.                 String s = key + " = " + values.toString() + "\n";  
  52.                 responseBody.write(s.getBytes());  
  53.             }  
  54.             responseBody.close();  
  55.         }  
  56.     }  
  57. }  

3、使用apache开源的httpcore组件实现。

[java] view plain copy
  1. /* 
  2.  * ==================================================================== 
  3.  * Licensed to the Apache Software Foundation (ASF) under one 
  4.  * or more contributor license agreements.  See the NOTICE file 
  5.  * distributed with this work for additional information 
  6.  * regarding copyright ownership.  The ASF licenses this file 
  7.  * to you under the Apache License, Version 2.0 (the 
  8.  * "License"); you may not use this file except in compliance 
  9.  * with the License.  You may obtain a copy of the License at 
  10.  * 
  11.  *   http://www.apache.org/licenses/LICENSE-2.0 
  12.  * 
  13.  * Unless required by applicable law or agreed to in writing, 
  14.  * software distributed under the License is distributed on an 
  15.  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 
  16.  * KIND, either express or implied.  See the License for the 
  17.  * specific language governing permissions and limitations 
  18.  * under the License. 
  19.  * ==================================================================== 
  20.  * 
  21.  * This software consists of voluntary contributions made by many 
  22.  * individuals on behalf of the Apache Software Foundation.  For more 
  23.  * information on the Apache Software Foundation, please see 
  24.  * <http://www.apache.org/>. 
  25.  * 
  26.  */  
  27.   
  28. package org.apache.http.examples;  
  29.   
  30. import java.io.File;  
  31. import java.io.IOException;  
  32. import java.io.InterruptedIOException;  
  33. import java.net.ServerSocket;  
  34. import java.net.Socket;  
  35. import java.net.URL;  
  36. import java.net.URLDecoder;  
  37. import java.nio.charset.Charset;  
  38. import java.security.KeyStore;  
  39. import java.util.Locale;  
  40.   
  41. import org.apache.http.ConnectionClosedException;  
  42. import org.apache.http.HttpConnectionFactory;  
  43. import org.apache.http.HttpEntity;  
  44. import org.apache.http.HttpEntityEnclosingRequest;  
  45. import org.apache.http.HttpException;  
  46. import org.apache.http.HttpRequest;  
  47. import org.apache.http.HttpResponse;  
  48. import org.apache.http.HttpServerConnection;  
  49. import org.apache.http.HttpStatus;  
  50. import org.apache.http.MethodNotSupportedException;  
  51. import org.apache.http.entity.ContentType;  
  52. import org.apache.http.entity.FileEntity;  
  53. import org.apache.http.entity.StringEntity;  
  54. import org.apache.http.impl.DefaultBHttpServerConnection;  
  55. import org.apache.http.impl.DefaultBHttpServerConnectionFactory;  
  56. import org.apache.http.protocol.BasicHttpContext;  
  57. import org.apache.http.protocol.HttpContext;  
  58. import org.apache.http.protocol.HttpProcessor;  
  59. import org.apache.http.protocol.HttpProcessorBuilder;  
  60. import org.apache.http.protocol.HttpRequestHandler;  
  61. import org.apache.http.protocol.HttpService;  
  62. import org.apache.http.protocol.ResponseConnControl;  
  63. import org.apache.http.protocol.ResponseContent;  
  64. import org.apache.http.protocol.ResponseDate;  
  65. import org.apache.http.protocol.ResponseServer;  
  66. import org.apache.http.protocol.UriHttpRequestHandlerMapper;  
  67. import org.apache.http.util.EntityUtils;  
  68.   
  69. import javax.net.ssl.KeyManager;  
  70. import javax.net.ssl.KeyManagerFactory;  
  71. import javax.net.ssl.SSLContext;  
  72. import javax.net.ssl.SSLServerSocketFactory;  
  73.   
  74. /** 
  75.  * Basic, yet fully functional and spec compliant, HTTP/1.1 file server. 
  76.  */  
  77. public class ElementalHttpServer {  
  78.   
  79.     public static void main(String[] args) throws Exception {  
  80.         /** 
  81.         if (args.length < 1) { 
  82.             System.err.println("Please specify document root directory"); 
  83.             System.exit(1); 
  84.         } 
  85.         // Document root directory 
  86.         String docRoot = args[0];*/  
  87.          String docRoot="c:/root";  
  88.         int port = 8080;  
  89.         if (args.length >= 2) {  
  90.             port = Integer.parseInt(args[1]);  
  91.         }  
  92.   
  93.         // Set up the HTTP protocol processor  
  94.         HttpProcessor httpproc = HttpProcessorBuilder.create()  
  95.                 .add(new ResponseDate())  
  96.                 .add(new ResponseServer("Test/1.1"))  
  97.                 .add(new ResponseContent())  
  98.                 .add(new ResponseConnControl()).build();  
  99.   
  100.         // Set up request handlers  
  101.         UriHttpRequestHandlerMapper reqistry = new UriHttpRequestHandlerMapper();  
  102.         reqistry.register("*"new HttpFileHandler(docRoot));  
  103.   
  104.         // Set up the HTTP service  
  105.         HttpService httpService = new HttpService(httpproc, reqistry);  
  106.   
  107.         SSLServerSocketFactory sf = null;  
  108.         if (port == 8443) {  
  109.             // Initialize SSL context  
  110.             ClassLoader cl = ElementalHttpServer.class.getClassLoader();  
  111.             URL url = cl.getResource("my.keystore");  
  112.             if (url == null) {  
  113.                 System.out.println("Keystore not found");  
  114.                 System.exit(1);  
  115.             }  
  116.             KeyStore keystore  = KeyStore.getInstance("jks");  
  117.             keystore.load(url.openStream(), "secret".toCharArray());  
  118.             KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(  
  119.                     KeyManagerFactory.getDefaultAlgorithm());  
  120.             kmfactory.init(keystore, "secret".toCharArray());  
  121.             KeyManager[] keymanagers = kmfactory.getKeyManagers();  
  122.             SSLContext sslcontext = SSLContext.getInstance("TLS");  
  123.             sslcontext.init(keymanagers, nullnull);  
  124.             sf = sslcontext.getServerSocketFactory();  
  125.         }  
  126.   
  127.         Thread t = new RequestListenerThread(port, httpService, sf);  
  128.         t.setDaemon(false);  
  129.         t.start();  
  130.     }  
  131.   
  132.     static class HttpFileHandler implements HttpRequestHandler  {  
  133.   
  134.         private final String docRoot;  
  135.   
  136.         public HttpFileHandler(final String docRoot) {  
  137.             super();  
  138.             this.docRoot = docRoot;  
  139.         }  
  140.   
  141.         public void handle(  
  142.                 final HttpRequest request,  
  143.                 final HttpResponse response,  
  144.                 final HttpContext context) throws HttpException, IOException {  
  145.   
  146.             String method = request.getRequestLine().getMethod().toUpperCase(Locale.ENGLISH);  
  147.             if (!method.equals("GET") && !method.equals("HEAD") && !method.equals("POST")) {  
  148.                 throw new MethodNotSupportedException(method + " method not supported");  
  149.             }  
  150.             String target = request.getRequestLine().getUri();  
  151.   
  152.             if (request instanceof HttpEntityEnclosingRequest) {  
  153.                 HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity();  
  154.                 byte[] entityContent = EntityUtils.toByteArray(entity);  
  155.                 System.out.println("Incoming entity content (bytes): " + entityContent.length);  
  156.             }  
  157.   
  158.             final File file = new File(this.docRoot, URLDecoder.decode(target, "UTF-8"));  
  159.             if (!file.exists()) {  
  160.   
  161.                 response.setStatusCode(HttpStatus.SC_NOT_FOUND);  
  162.                 StringEntity entity = new StringEntity(  
  163.                         "<html><body><h1>File" + file.getPath() +  
  164.                         " not found</h1></body></html>",  
  165.                         ContentType.create("text/html""UTF-8"));  
  166.                 response.setEntity(entity);  
  167.                 System.out.println("File " + file.getPath() + " not found");  
  168.   
  169.             } else if (!file.canRead() || file.isDirectory()) {  
  170.   
  171.                 response.setStatusCode(HttpStatus.SC_FORBIDDEN);  
  172.                 StringEntity entity = new StringEntity(  
  173.                         "<html><body><h1>Access denied</h1></body></html>",  
  174.                         ContentType.create("text/html""UTF-8"));  
  175.                 response.setEntity(entity);  
  176.                 System.out.println("Cannot read file " + file.getPath());  
  177.   
  178.             } else {  
  179.   
  180.                 response.setStatusCode(HttpStatus.SC_OK);  
  181.                 FileEntity body = new FileEntity(file, ContentType.create("text/html", (Charset) null));  
  182.                 response.setEntity(body);  
  183.                 System.out.println("Serving file " + file.getPath());  
  184.             }  
  185.         }  
  186.   
  187.     }  
  188.   
  189.     static class RequestListenerThread extends Thread {  
  190.   
  191.         private final HttpConnectionFactory<DefaultBHttpServerConnection> connFactory;  
  192.         private final ServerSocket serversocket;  
  193.         private final HttpService httpService;  
  194.   
  195.         public RequestListenerThread(  
  196.                 final int port,  
  197.                 final HttpService httpService,  
  198.                 final SSLServerSocketFactory sf) throws IOException {  
  199.             this.connFactory = DefaultBHttpServerConnectionFactory.INSTANCE;  
  200.             this.serversocket = sf != null ? sf.createServerSocket(port) : new ServerSocket(port);  
  201.             this.httpService = httpService;  
  202.         }  
  203.   
  204.         @Override  
  205.         public void run() {  
  206.             System.out.println("Listening on port " + this.serversocket.getLocalPort());  
  207.             while (!Thread.interrupted()) {  
  208.                 try {  
  209.                     // Set up HTTP connection  
  210.                     Socket socket = this.serversocket.accept();  
  211.                     System.out.println("Incoming connection from " + socket.getInetAddress());  
  212.                     HttpServerConnection conn = this.connFactory.createConnection(socket);  
  213.   
  214.                     // Start worker thread  
  215.                     Thread t = new WorkerThread(this.httpService, conn);  
  216.                     t.setDaemon(true);  
  217.                     t.start();  
  218.                 } catch (InterruptedIOException ex) {  
  219.                     break;  
  220.                 } catch (IOException e) {  
  221.                     System.err.println("I/O error initialising connection thread: "  
  222.                             + e.getMessage());  
  223.                     break;  
  224.                 }  
  225.             }  
  226.         }  
  227.     }  
  228.   
  229.     static class WorkerThread extends Thread {  
  230.   
  231.         private final HttpService httpservice;  
  232.         private final HttpServerConnection conn;  
  233.   
  234.         public WorkerThread(  
  235.                 final HttpService httpservice,  
  236.                 final HttpServerConnection conn) {  
  237.             super();  
  238.             this.httpservice = httpservice;  
  239.             this.conn = conn;  
  240.         }  
  241.   
  242.         @Override  
  243.         public void run() {  
  244.             System.out.println("New connection thread");  
  245.             HttpContext context = new BasicHttpContext(null);  
  246.             try {  
  247.                 while (!Thread.interrupted() && this.conn.isOpen()) {  
  248.                     this.httpservice.handleRequest(this.conn, context);  
  249.                 }  
  250.             } catch (ConnectionClosedException ex) {  
  251.                 System.err.println("Client closed connection");  
  252.             } catch (IOException ex) {  
  253.                 System.err.println("I/O error: " + ex.getMessage());  
  254.             } catch (HttpException ex) {  
  255.                 System.err.println("Unrecoverable HTTP protocol violation: " + ex.getMessage());  
  256.             } finally {  
  257.                 try {  
  258.                     this.conn.shutdown();  
  259.                 } catch (IOException ignore) {}  
  260.             }  
  261.         }  
  262.   
  263.     }  
  264.   
  265. }  

下面附上源码下载:http://download.csdn.net/detail/earbao/6560673

0 0
原创粉丝点击