在java的官方文档中有一个实现的简单的web服务器,我把他稍加润色,试一下一个简单的web服务器,源码如下:
import com.sun.net.httpserver.*; import java.net.*; import java.io.*; class MyHandler implements HttpHandler { public void handle(HttpExchange t) throws IOException { //InputStream is = t.getRequestBody(); //read(is); String response = "This is the response"; t.sendResponseHeaders(200,response.length()); OutputStream os = t.getResponseBody(); os.write(response.getBytes()); os.close(); } } public class MyServer { public static void main(String argv[]) //throws IOException { try { HttpServer server = HttpServer.create(new InetSocketAddress(8000),0); server.createContext("/myapp",new MyHandler()); server.setExecutor(null); server.start(); } catch (IOException e) { e.printStackTrace(); } } } |