V4V3的基础上实现了ServletConfigServletContext接口,从而实现了Servlet实例化初始化BinCatDispatcherServlet实现的Servlet服务调用。
    BinCatServerV4实现代码:

    1. package com.anbai.sec.server;
    2. import com.anbai.sec.server.config.BinCatConfig;
    3. import com.anbai.sec.server.handler.BinCatDispatcherServlet;
    4. import com.anbai.sec.server.handler.BinCatResponseHandler;
    5. import com.anbai.sec.server.servlet.BinCatRequest;
    6. import com.anbai.sec.server.servlet.BinCatResponse;
    7. import com.anbai.sec.server.servlet.BinCatServletContext;
    8. import java.io.ByteArrayOutputStream;
    9. import java.io.InputStream;
    10. import java.io.OutputStream;
    11. import java.net.ServerSocket;
    12. import java.net.Socket;
    13. import java.util.Map;
    14. import java.util.concurrent.ConcurrentHashMap;
    15. import java.util.logging.Logger;
    16. /**
    17. * ServerSocket Http 服务器示例
    18. */
    19. public class BinCatServerV4 {
    20. // 设置服务监听端口
    21. private static final int PORT = 8080;
    22. // 设置服务名称
    23. private static final String SERVER_NAME = "BinCat-0.0.4";
    24. private static final Logger LOG = Logger.getLogger("info");
    25. public static void main(String[] args) {
    26. try {
    27. // 创建ServerSocket,监听本地端口
    28. ServerSocket ss = new ServerSocket(PORT);
    29. // 创建BinCatServletContext对象
    30. BinCatServletContext servletContext = BinCatConfig.createServletContext();
    31. // 初始化Servlet
    32. BinCatConfig.initServlet(servletContext);
    33. LOG.info(SERVER_NAME + " 启动成功,监听端口: " + PORT);
    34. while (true) {
    35. // 等待客户端连接
    36. Socket socket = ss.accept();
    37. try {
    38. // 获取Socket输入流对象
    39. InputStream in = socket.getInputStream();
    40. // 获取Socket输出流对象
    41. OutputStream out = socket.getOutputStream();
    42. // 创建BinCat请求处理对象
    43. BinCatRequest request = new BinCatRequest(socket, servletContext);
    44. // 创建BinCat请求处理结果输出流
    45. ByteArrayOutputStream baos = new ByteArrayOutputStream();
    46. // 创建BinCat请求处理结果Header对象
    47. Map<String, String> responseHeader = new ConcurrentHashMap<String, String>();
    48. // 创建BinCat响应处理对象
    49. BinCatResponse response = new BinCatResponse(socket, responseHeader, baos);
    50. // 创建BinCatDispatcherServlet对象,用于分发Http请求
    51. BinCatDispatcherServlet dispatcherServlet = new BinCatDispatcherServlet();
    52. // 创建BinCatResponseHandler对象,用于处理Http请求结果
    53. BinCatResponseHandler responseHandler = new BinCatResponseHandler();
    54. // 使用BinCatDispatcherServlet处理Servlet请求
    55. dispatcherServlet.doDispatch(request, response, baos);
    56. // 响应服务器处理结果
    57. responseHandler.processResult(response, responseHeader, SERVER_NAME, out, baos);
    58. in.close();
    59. out.close();
    60. } catch (Exception e) {
    61. LOG.info("处理客户端请求异常:" + e);
    62. } finally {
    63. socket.close();
    64. }
    65. }
    66. } catch (Exception e) {
    67. e.printStackTrace();
    68. }
    69. }
    70. }