2017-04-17

Java中HttpServer (HttpsServer) ,解決response會延遲或卡住的問題

第一次使用 com.sun.net.httpserver.HttpServer 跟 com.sun.net.httpserver.HttpsServer 做為http server時,
發現連續的request會使得response卡住:

OutputStream os = httpExchange.getResponseBody();
os.write(response.getBytes()); //卡住造成阻塞,過很久才會回應,
os.close();

解決之道,就是確保connection能close, 並使用multi-thread:
final Executor multi = Executors.newFixedThreadPool(10);
final HttpServer server = HttpServer.create(new InetSocketAddress(s_HTTP_PORT), 5);
//... do your REST bindings here
server.setExecutor(multi);
server.start();

//bindings中送出Connection = close 的 header
httpExchange.getResponseHeaders().add("Connection", "close");


ref:
http://stackoverflow.com/questions/15235075/1s-delay-in-httpserver-since-java-7

沒有留言:

張貼留言