package com.yang;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
public class MyHTTPServer {
public static void main(String[] args) {
try {
HttpServer hs = HttpServer.create(new InetSocketAddress(8888), 0);// 设置HttpServer的端口为8888
hs.createContext("/yang", new MyHandler());// 用MyHandler类内处理到//hujun的请求
hs.setExecutor(null); // creates a default executor
hs.start();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
class MyHandler implements HttpHandler {
public void handle(HttpExchange t) throws IOException {
InputStream is = t.getRequestBody();
String response = "come on baby";
t.sendResponseHeaders(200, response.length());
OutputStream os = t.getResponseBody();
os.write(response.getBytes());
os.close();
}
}
以上这段经典的入门代码,不知道有没大侠在改造时,对其进行过压力测试,
在本人的项目中,我发现HttpHandler对于请求的处理,是串行的。
也就是每处理完一个handle(HttpExchange t),才能接受一个新的请求。
在处理请求的过程中,对新的请求是处于阻塞状态
无法做到多线程的并发处理,这样也就压缩了其使用的范围。
请大家拍砖