HttpServer HTTP服务器(netty\tomcat\nginx)

330 阅读3分钟

一、HttpServer HTTP服务器

Web Server,但说到HTTP Server却很少有人知道,那么HTTP Server是什么呢?

一般来说,HTTP Server 也是我们常说的Web服务器,大名鼎鼎的 Apache,还有微软的 IIS (Internet Information Server),开源领域的有 Lighttpd 和最近风头正劲的 Nginx 都是典型的Web服务器。

定义

HTTP SERVER就是网页服务器,也称网站服务器,是指在互联网数据中心中存放网站的服务器,主要用于网站的互联网中的发布、应用,是网络应用的基础硬件设施。网站服务器可根据网站应用的需要,部署搭建ASP、JSP、NET、PHP等应用环境。

目前流行两种环境一种是LAMP环境,另一种是 WINDOWS加 IIS加 ASP或.NET加MSSQL环境,

LAMP为现在使用最广的服务器环境,它运行在Linux系统下,稳定、安全,APACHE是最著名的开源网页服务器

HttpServer类实现一个简单的HTTP服务器。HttpServer绑定到IP地址和端口号,并侦听此地址上来自客户端的传入TCP连接。该子类HttpsServer实现了一个处理HTTPS请求的服务器。

一个或多个HttpHandler对象必须与服务器关联才能处理请求。每个此类HttpHandler都注册有一个根URI路径,该路径表示应用程序或服务在此服务器上的位置。处理程序到HttpServer的映射由HttpContext对象封装。HttpContext是通过调用创建的createContext(String,HttpHandler)。找不到任何处理程序的任何请求都会被404响应拒绝。

示例代码


@Component
public class CacheRunner implements ApplicationRunner {
 
    @Value("${frReport.PRIVATE.KEY}")
    private String privateKey;
 
 
  String keyStoreFilePath = "/root/.ssl/test.pkcs12";
  String keyStorePassword = "Password@123456";
 

    @Override
    public void run(ApplicationArguments applicationArguments) throws Exception {
           //todo  缓存数据

        try {
            //服务器ip,后期ip:8080 转成https 域名调用 
            InetAddress address = InetAddress.getLocalHost();
            HttpServer server = HttpServer.create(new InetSocketAddress(address, 8080), 0);

            server.createContext("/fineRept", new FRHttpAuthenticationHandler(FRCompanyNO, privateKey));
            
            
            server.setExecutor(null); // creates a default executor
            server.start();
            System.out.println("帆软报表登录认证服务器已启动");
            HttpsServer hss = HttpsServer.create(new InetSocketAddress(address, 443), 0);
        
         
try {
            KeyStore keyStore = KeyStore.getInstance("PKCS12"); //建立证书库
            keyStore.load(new FileInputStream(keyStoreFilePath), keyStorePassword.toCharArray());

            KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            keyManagerFactory.init(keyStore, keyStorePassword.toCharArray());

            sslContext = SslContextBuilder.forServer(keyManagerFactory).build();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        
        HttpsConfigurator conf =HttpsConfigurator(sslContext);
        hss.setHttpsConfigurator(conf);
        hss.createContext("/", new FRHttpAuthenticationHandler(FRCompanyNO, privateKey));
            
            
        } catch (IOException e) {
            e.printStackTrace();
            LogUtil.writeExceptionLog(new MLogException(ExceptionLevel.Error, "fineReportSso", e.getMessage(), e));
        }
    }
}



@Component
public class FRHttpAuthenticationHandler implements HttpHandler {
    private String FRCompanyNO;
    private String privateKey;

    public FRHttpAuthenticationHandler() {
    }

    public FRHttpAuthenticationHandler(String FRCompanyNO, String privateKey) {
        this.FRCompanyNO = FRCompanyNO;
        this.privateKey = privateKey;
    }

    @Override
    public void handle(HttpExchange httpExchange) throws IOException {
        httpExchange.sendResponseHeaders(200, 0);
        httpExchange.getResponseHeaders().set("Content-Type", "text/plain");
        URI uri = httpExchange.getRequestURI();
        String data = getData(uri.getQuery());
        OutputStream os = httpExchange.getResponseBody();
        long begin = System.currentTimeMillis();
        String emsgReturnValue = "";
        HashMap<String, String> dataMap = new HashMap<>();
        try {
            if ("".equals(data)) {
                os.write("error".getBytes());
                os.close();
                emsgReturnValue = "解析数据结果为空";
                return;
            }
            ObjectMapper Mapper = new ObjectMapper();
            JsonNode root = Mapper.readTree(RsaUtil.decrypt(URLDecoder.decode(data, "UTF-8"), privateKey));
            String fr_username = root.path("username").asText();
            String fr_password = root.path("password").asText();
            String uuid = root.path("uuid").asText();

            dataMap.put("fr_username", fr_username);
            dataMap.put("fr_password", fr_password);
            if (isCodeErr(dataMap)) {//登录成功清除redis\springsession 等信息。只能用一次
                os.write(RsaUtil.encrypt("{"success":"false"}", privateKey));
                os.close();
                emsgReturnValue = "校验账号密码失败";
                return;
            }

            os.write(RsaUtil.encrypt("{"success":"true","uuid":"" + uuid + ""}", privateKey));
            os.close();
            emsgReturnValue = "true";
        } catch (Exception ex) {
        
            os.write(RsaUtil.encrypt("{"success":"false"}", privateKey));
         } finally {
            os.close();
        }
    }



二、 内置jetty实现Httpserver

Jetty 是一个开源的servlet容器,它为基于Java的web内容,例如JSP和servlet提供运行环境。Jetty是使用Java语言编写的,它的API以一组JAR包的形式发布。开发人员可以将Jetty容器实例化成一个对象,可以迅速为一些独立运行(stand-alone)的Java应用提供网络和web连接。   

需要最少的包:     commons-logging.jar    javax.servlet.jar     org.mortbay.jetty.jar     org.mortbay.jmx.jar



 try {
            // 进行服务器配置
            Server server = new Server(8080);
            ContextHandler context = new ContextHandler();
            // 设置搜索的URL地址
            context.setContextPath("/search");
            context.setResourceBase(".");
            context.setClassLoader(Thread.currentThread()
                    .getContextClassLoader());
            server.setHandler(context);
            context.setHandler(new HelloHandler());
            // 启动服务器
            server.start();
            server.join();
        } catch (Exception e) {
            e.printStackTrace();
        }
        

import org.mortbay.http.HttpContext;   
import org.mortbay.http.HttpServer;   
import org.mortbay.http.SocketListener;   
import org.mortbay.http.handler.ResourceHandler;   
public class JettySample {   
  public static void main(String[] args) throws Exception   
  {   
    //创建Jetty HttpServer对象   
    HttpServer server = new HttpServer();   
    //在端口8080上给HttpServer对象绑上一个listener,使之能够接收HTTP请求   
    SocketListener listener = new SocketListener();   
    listener.setPort(8080);   
    server.addListener(listener);   
     
    //创建一个HttpContext,处理HTTP请求。   
    HttpContext context = new HttpContext();   
    //用setContextPath把Context映射到(/web)URL上。   
    context.setContextPath("/fineReport");   
    //setResourceBase方法设置文档目录以提供资源   
    context.setResourceBase("C:\\j2sdk1.4.1_05");   
    //添加资源处理器到HttpContext,使之能够提供文件系统中的文件   
    context.addHandler(new ResourceHandler());   
    server.addContext(context);   
    //启动服务器   
    server.start();   
  }   
}   


class HelloHandler extends AbstractHandler {

    @Override
    public void handle(String target, Request baseRequest,
            HttpServletRequest request, HttpServletResponse response)
            throws IOException, ServletException {

        /**
         * <pre>
         * 从 URL 里面得到传递过来的参数: 
         *  http://localhost:8080/search?query=hello 
         * 如果你需要传递更多的参数,可以这么写: 
         *  http://localhost:8080/search?query=hello&name=ZhangLili 
         * 从这里开始,你可以写自己的代码逻辑。 
         *  
         * [注意:GET方法的请求,URL 的最大长度是 1024个字节]
         * </pre>
         */

        String query = request.getParameter("query");
        // String name = request.getParameter("name");

        String result = "welcome to my server.";
        if (null != query && query.equals("hello")) {
            result = query + ", " + result;
        }

        // 将服务器处理后的结果返回给调用URL的客户端
        print(baseRequest, response, result);
    }

    /**
     * <pre>
     * @param baseRequest 
     * @param response 
     * @param result 需要返回给客户的结果 
     * @throws IOException 
     * 将结果 result 返回给客户
     * </pre>
     */
    private void print(Request baseRequest, HttpServletResponse response,
            String result) throws IOException {
        response.setContentType("text/json;charset=utf-8");
        response.setStatus(HttpServletResponse.SC_OK);
        baseRequest.setHandled(true);
        response.getWriter().println(result);
    } 
 

三、 Tomcat

Tomcat和HTTP Server都是属于Apache软件基金会下的项目

四、Nginx

Nginx是一款开源软件,遵循BSD许可,可以作为HTTP服务器、邮件代理服务器、通用TCP代理服务器,绑定IP地址并监听TCP端口