Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

In order to close connections on the server side using Java HttpServer, you can make use of the HttpExchange class. The HttpExchange class provides a method called close(), which can be used to close the connection.

Here is some sample code to close connections on the server side using Java HttpServer:

import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.util.concurrent.Executors;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;

public class HttpServerExample {

    public static void main(String[] args) throws Exception {

        HttpServer server = HttpServer.create(new InetSocketAddress(8000), 0);

        server.createContext("/", new MyHandler());

        server.setExecutor(Executors.newFixedThreadPool(10));

        server.start();

        System.out.println("Server started on port 8000");

    }

    static class MyHandler implements HttpHandler {

        @Override
        public void handle(HttpExchange exchange) throws IOException {

            // Close the connection
            exchange.close();

        }

    }

}

In the above code, when a request is received by the server, the handle() method of the MyHandler class is invoked. Here, we have simply called the close() method on the HttpExchange object, which will effectively close the connection on the server side.