com.sun.net.httpserver.HttpServer类的使用及代码示例

x33g5p2x  于2022-01-20 转载在 其他  
字(11.4k)|赞(0)|评价(0)|浏览(323)

本文整理了Java中com.sun.net.httpserver.HttpServer类的一些代码示例,展示了HttpServer类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。HttpServer类的具体详情如下:
包路径:com.sun.net.httpserver.HttpServer
类名称:HttpServer

HttpServer介绍

[英]This class implements a simple HTTP server. A HttpServer is bound to an IP address and port number and listens for incoming TCP connections from clients on this address. The sub-class HttpsServer implements a server which handles HTTPS requests.

One or more HttpHandler objects must be associated with a server in order to process requests. Each such HttpHandler is registered with a root URI path which represents the location of the application or service on this server. The mapping of a handler to a HttpServer is encapsulated by a HttpContext object. HttpContexts are created by calling #createContext(String,HttpHandler). Any request for which no handler can be found is rejected with a 404 response. Management of threads can be done external to this object by providing a java.util.concurrent.Executor object. If none is provided a default implementation is used.

Mapping request URIs to HttpContext paths

When a HTTP request is received, the appropriate HttpContext (and handler) is located by finding the context whose path is the longest matching prefix of the request URI's path. Paths are matched literally, which means that the strings are compared case sensitively, and with no conversion to or from any encoded forms. For example. Given a HttpServer with the following HttpContexts configured.

ContextContext pathctx1"/"ctx2"/apps/"ctx3"/apps/foo/"

the following table shows some request URIs and which, if any context they would match with.

Request URIMatches context"http://foo.com/apps/foo/bar"ctx3"http://foo.com/apps/Foo/bar"no match, wrong case"http://foo.com/apps/app1"ctx2"http://foo.com/foo"ctx1

Note about socket backlogs

When binding to an address and port number, the application can also specify an integer backlog parameter. This represents the maximum number of incoming TCP connections which the system will queue internally. Connections are queued while they are waiting to be accepted by the HttpServer. When the limit is reached, further connections may be rejected (or possibly ignored) by the underlying TCP implementation. Setting the right backlog value is a compromise between efficient resource usage in the TCP layer (not setting it too high) and allowing adequate throughput of incoming requests (not setting it too low).
[中]此类实现了一个简单的HTTP服务器。HttpServer绑定到IP地址和端口号,并在此地址上侦听来自客户端的传入TCP连接。子类HttpsServer实现了一个处理HTTPS请求的服务器。
为了处理请求,必须将一个或多个HttpHandler对象与服务器关联。每个这样的HttpHandler都使用根URI路径注册,该路径表示此服务器上应用程序或服务的位置。处理程序到HttpServer的映射由HttpContext对象封装。HttpContext是通过调用#createContext(字符串,HttpHandler)创建的。任何找不到处理程序的请求都会被404响应拒绝。线程的管理可以在这个对象外部通过提供一个java脚本来完成。util。同时发生的执行对象。如果没有提供,则使用默认实现。
将请求URI映射到HttpContext路径
当接收到HTTP请求时,通过查找其路径是请求URI路径的最长匹配前缀的上下文来定位适当的HttpContext(和处理程序)。路径是逐字匹配的,这意味着字符串区分大小写进行比较,并且不与任何编码形式进行转换。例如给定配置了以下HttpContext的HttpServer。
ContextContext路径ctx1“/ctx2”/apps/“ctx3”/apps/foo/“
下表显示了一些请求URI以及它们将与之匹配的上下文(如果有的话)。
请求“匹配上下文”http://foo.com/apps/foo/bar“ctx3”http://foo.com/apps/Foo/bar“不匹配,错误案例”http://foo.com/apps/app1“ctx2”http://foo.com/foo“ctx1
关于套接字积压的注意事项
当绑定到地址和端口号时,应用程序还可以指定一个整数backlog参数。这表示系统将在内部排队的最大传入TCP连接数。连接在等待HttpServer接受时排队。当达到限制时,底层TCP实现可能会拒绝(或可能忽略)进一步的连接。设置正确的backlog值是TCP层中高效资源使用(不要设置得太高)和允许足够的传入请求吞吐量(不要设置得太低)之间的折衷。

代码示例

代码示例来源:origin: Netflix/eureka

public SimpleEurekaHttpServer(EurekaHttpClient requestHandler, EurekaTransportEventListener eventListener) throws IOException {
  this.requestHandler = requestHandler;
  this.eventListener = eventListener;
  this.httpServer = HttpServer.create(new InetSocketAddress(0), 1);
  httpServer.createContext("/v2", createEurekaV2Handle());
  httpServer.setExecutor(null);
  httpServer.start();
}

代码示例来源:origin: spring-projects/spring-framework

@Override
public void destroy() {
  logger.info("Stopping HttpServer");
  this.server.stop(this.shutdownDelay);
}

代码示例来源:origin: Netflix/eureka

public int getServerPort() {
  return httpServer.getAddress().getPort();
}

代码示例来源:origin: spring-projects/spring-framework

@Override
public void afterPropertiesSet() throws Exception {
  if (this.server == null) {
    InetSocketAddress address = (this.hostname != null ?
        new InetSocketAddress(this.hostname, this.port) : new InetSocketAddress(this.port));
    HttpServer server = HttpServer.create(address, this.backlog);
    if (logger.isInfoEnabled()) {
      logger.info("Starting HttpServer at address " + address);
    }
    server.start();
    this.server = server;
    this.localServer = true;
  }
  super.afterPropertiesSet();
}

代码示例来源:origin: jersey/jersey

@Override
public void start() {
  if (started.compareAndSet(false, true)) {
    LOGGER.log(Level.FINE, "Starting JdkHttpServerTestContainer...");
    server.start();
    if (baseUri.getPort() == 0) {
      baseUri = UriBuilder.fromUri(baseUri)
          .port(server.getAddress().getPort())
          .build();
      LOGGER.log(Level.INFO, "Started JdkHttpServerTestContainer at the base URI " + baseUri);
    }
  } else {
    LOGGER.log(Level.WARNING, "Ignoring start request - JdkHttpServerTestContainer is already started.");
  }
}

代码示例来源:origin: rhuss/jolokia

/**
 * Create the HttpServer to use. Can be overridden if a custom or already existing HttpServer should be
 * used
 *
 * @return HttpServer to use
 * @throws IOException if something fails during the initialisation
 */
private HttpServer createHttpServer(JolokiaServerConfig pConfig) throws IOException {
  int port = pConfig.getPort();
  InetAddress address = pConfig.getAddress();
  InetSocketAddress socketAddress = new InetSocketAddress(address,port);
  HttpServer server = pConfig.useHttps() ?
          createHttpsServer(socketAddress, pConfig) :
          HttpServer.create(socketAddress, pConfig.getBacklog());
  // Thread factory which creates only daemon threads
  ThreadFactory daemonThreadFactory = new DaemonThreadFactory(pConfig.getThreadNamePrefix());
  // Prepare executor pool
  Executor executor;
  String mode = pConfig.getExecutor();
  if ("fixed".equalsIgnoreCase(mode)) {
    executor = Executors.newFixedThreadPool(pConfig.getThreadNr(), daemonThreadFactory);
  } else if ("cached".equalsIgnoreCase(mode)) {
    executor = Executors.newCachedThreadPool(daemonThreadFactory);
  } else {
    executor = Executors.newSingleThreadExecutor(daemonThreadFactory);
  }
  server.setExecutor(executor);
  return server;
}

代码示例来源:origin: apache/incubator-pinot

private HttpServer startServer(int port, HttpHandler handler)
  throws IOException {
 final HttpServer server = HttpServer.create(new InetSocketAddress(port), 0);
 server.createContext(URI_PATH, handler);
 new Thread(new Runnable() {
  @Override
  public void run() {
   server.start();
  }
 }).start();
 return server;
}

代码示例来源:origin: prometheus/client_java

/**
 * Start a HTTP server serving Prometheus metrics from the given registry.
 */
public HTTPServer(InetSocketAddress addr, CollectorRegistry registry, boolean daemon) throws IOException {
  server = HttpServer.create();
  server.bind(addr, 3);
  HttpHandler mHandler = new HTTPMetricHandler(registry);
  server.createContext("/", mHandler);
  server.createContext("/metrics", mHandler);
  executorService = Executors.newFixedThreadPool(5, NamedDaemonThreadFactory.defaultThreadFactory(daemon));
  server.setExecutor(executorService);
  start(daemon);
}

代码示例来源:origin: apache/ignite

/**
 * Returns base server url in the form <i>protocol://serverHostName:serverPort</i>.
 *
 * @return Base server url.
 */
public String getBaseUrl() {
  return proto + "://" + httpSrv.getAddress().getHostName() + ":" + httpSrv.getAddress().getPort();
}

代码示例来源:origin: rhuss/jolokia

private String detectAgentUrl(HttpServer pServer, JolokiaServerConfig pConfig, String pContextPath) {
  serverAddress= pServer.getAddress();
  InetAddress realAddress;
  int port;
  if (serverAddress != null) {
    realAddress = serverAddress.getAddress();
    if (realAddress.isAnyLocalAddress()) {
      try {
        realAddress = NetworkUtil.getLocalAddress();
      } catch (IOException e) {
        try {
          realAddress = InetAddress.getLocalHost();
        } catch (UnknownHostException e1) {
          // Ok, ok. We take the original one
          realAddress = serverAddress.getAddress();
        }
      }
    }
    port = serverAddress.getPort();
  } else {
    realAddress = pConfig.getAddress();
    port = pConfig.getPort();
  }
  return String.format("%s://%s:%d%s",
             pConfig.getProtocol(),realAddress.getHostAddress(),port, pContextPath);
}

代码示例来源:origin: mpusher/alloc

@Override
public void init() {
  int port = CC.mp.net.cfg.getInt("alloc-server-port");
  boolean https = "https".equals(CC.mp.net.cfg.getString("alloc-server-protocol"));
  this.httpServer = HttpServerCreator.createServer(port, https);
  this.allocHandler = new AllocHandler();
  this.pushHandler = new PushHandler();
  httpServer.setExecutor(Executors.newCachedThreadPool());//设置线程池,由于是纯内存操作,不需要队列
  httpServer.createContext("/", allocHandler);//查询mpush机器
  httpServer.createContext("/push", pushHandler);//模拟发送push
  httpServer.createContext("/index.html", new IndexPageHandler());//查询mpush机器
}

代码示例来源:origin: com.github.martinpaljak/apdu4j

public void start(InetSocketAddress address) throws IOException {
  server = HttpServer.create(address, Integer.parseInt(System.getProperty(BACKLOG, "10")));
  // threadpool!
  server.setExecutor(Executors.newWorkStealingPool(Integer.parseInt(System.getProperty(HTTPPOOL, "10"))));
  // Only two handlers.
  server.createContext("/", new MsgHandler());
  server.createContext("/status", new StatusHandler());
  logger.info("Server started on {} ", server.getAddress());
  // Starts in separate thread.
  server.start();
}

代码示例来源:origin: apache/cloudstack

private static void startupHttpMain() {
  try {
    ConsoleProxyServerFactory factory = getHttpServerFactory();
    if (factory == null) {
      s_logger.error("Unable to load HTTP server factory");
      System.exit(1);
    }
    HttpServer server = factory.createHttpServerInstance(httpListenPort);
    server.createContext("/getscreen", new ConsoleProxyThumbnailHandler());
    server.createContext("/resource/", new ConsoleProxyResourceHandler());
    server.createContext("/ajax", new ConsoleProxyAjaxHandler());
    server.createContext("/ajaximg", new ConsoleProxyAjaxImageHandler());
    server.setExecutor(new ThreadExecutor()); // creates a default executor
    server.start();
  } catch (Exception e) {
    s_logger.error(e.getMessage(), e);
    System.exit(1);
  }
}

代码示例来源:origin: googleapis/google-cloud-java

/** Starts the thread that runs the Resource Manager server. */
public void start() {
 server.start();
}

代码示例来源:origin: jersey/jersey

@Override
public HttpContext createContext(final String s) {
  return delegate.createContext(s);
}

代码示例来源:origin: jersey/jersey

@Override
public void setExecutor(final Executor executor) {
  delegate.setExecutor(executor);
}

代码示例来源:origin: jersey/jersey

@Override
  public InetSocketAddress getAddress() {
    return delegate.getAddress();
  }
};

代码示例来源:origin: org.springframework/spring-web

@Override
public void afterPropertiesSet() throws Exception {
  if (this.server == null) {
    InetSocketAddress address = (this.hostname != null ?
        new InetSocketAddress(this.hostname, this.port) : new InetSocketAddress(this.port));
    HttpServer server = HttpServer.create(address, this.backlog);
    if (logger.isInfoEnabled()) {
      logger.info("Starting HttpServer at address " + address);
    }
    server.start();
    this.server = server;
    this.localServer = true;
  }
  super.afterPropertiesSet();
}

代码示例来源:origin: apache/incubator-pinot

private HttpServer startServer(int port, HttpHandler handler)
  throws IOException {
 final HttpServer server = HttpServer.create(new InetSocketAddress(port), 0);
 server.createContext(URI_PATH, handler);
 new Thread(new Runnable() {
  @Override
  public void run() {
   server.start();
  }
 }).start();
 servers.add(server);
 return server;
}

代码示例来源:origin: io.prometheus/simpleclient_httpserver

/**
 * Start a HTTP server serving Prometheus metrics from the given registry.
 */
public HTTPServer(InetSocketAddress addr, CollectorRegistry registry, boolean daemon) throws IOException {
  server = HttpServer.create();
  server.bind(addr, 3);
  HttpHandler mHandler = new HTTPMetricHandler(registry);
  server.createContext("/", mHandler);
  server.createContext("/metrics", mHandler);
  executorService = Executors.newFixedThreadPool(5, DaemonThreadFactory.defaultThreadFactory(daemon));
  server.setExecutor(executorService);
  start(daemon);
}

相关文章