Ask Your Question
4

How can connections be closed on the server side using Java HttpServer?

asked 2022-05-22 11:00:00 +0000

devzero gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2022-03-03 15:00:00 +0000

lakamha gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-05-22 11:00:00 +0000

Seen: 8 times

Last updated: Mar 03 '22