Dear Wiki user, You have subscribed to a wiki page or wiki category on "Httpcomponents Wiki" for change notification.
The following page has been changed by OlegKalnichevski: http://wiki.apache.org/HttpComponents/HttpCoreTutorial ------------------------------------------------------------------------------ === Listening I/O reactors === - ListeningIOReactor and ListenerEndpoint interfaces + !ListeningIOReactor represents an I/O reactor capable of listening for incoming connections on one or several ports. + + {{{ + ListeningIOReactor ioreactor; + + ListenerEndpoint ep1 = ioreactor.listen(new InetSocketAddress(8081)); + ListenerEndpoint ep2 = ioreactor.listen(new InetSocketAddress(8082)); + ListenerEndpoint ep3 = ioreactor.listen(new InetSocketAddress(8083)); + + // Wait until all endpoints are up + ep1.waitFor(); + ep2.waitFor(); + ep3.waitFor(); + }}} + + Once an enpoint is fully intialized it starts accepting incoming connections and propagate I/O activity notifications to the !IOEventDispatch instance. + + One can obtain a set of registered endpoints at runtime, query the status of an endpoint at runtime, and close it if desired. + + {{{ + ListeningIOReactor ioreactor; + + Set<ListenerEndpoint> eps = ioreactor.getEndpoints(); + for (ListenerEndpoint ep: eps) { + // Still active? + System.out.println(ep.getAddress()); + if (ep.isClosed()) { + // If not, has it terminated due to an exception? + if (ep.getException() != null) { + ep.getException().printStackTrace(); + } + } else { + ep.close(); + } + } + }}} === ConnectingIOReactor I/O reactors === - ConnectingIOReactor, SessionRequest and SessionRequestCallback interfaces + !ConnectingIOReactor represents an I/O reactor capable of establishing connections with remote hosts. + + {{{ + ConnectingIOReactor ioreactor; + + SessionRequest sessionRequest = ioreactor.connect( + new InetSocketAddress("www.google.com", 80), null, null, null); + }}} + + Opening a connection to a remote host usually tends to be a time consuming process and may take a while to complete. One can monitor and control the process of session initialization by means of the !SessionRequest interface. + + {{{ + // Make sure the request times out if no connection established after 1 sec + sessionRequest.setConnectTimeout(1000); + // Wait for the request to complete + sessionRequest.waitFor(); + // Has request terminated due to an exception? + if (sessionRequest.getException() != null) { + sessionRequest.getException().printStackTrace(); + } + // Get hold of the new I/O session + IOSession iosession = sessionRequest.getSession(); + }}} + + !SessionRequest implementations are expected to be threading safe. Session request can be aborted at any time by calling !IOSession#cancel() from another thread of execution. + + {{{ + if (!sessionRequest.isCompleted()) { + sessionRequest.cancel(); + } + }}} + + One can pass several optional parameters to the #connect() method to exert a greater control over the process of session initialization. + + A non-null local socket address parameter can be used to bind the socket to a specific local address. + + {{{ + ConnectingIOReactor ioreactor; + + SessionRequest sessionRequest = ioreactor.connect( + new InetSocketAddress("www.google.com", 80), + new InetSocketAddress("192.168.0.10", 1234), null, null); + }}} + + One can provide a attachment object, which will be added to the new session's context upon initialization. This object can be used to pass an initial processing state to the protocol handler. + + {{{ + SessionRequest sessionRequest = ioreactor.connect( + new InetSocketAddress("www.google.com", 80), + null, new HttpHost("www.google.ru"), null); + + IOSession iosession = sessionRequest.getSession(); + HttpHost virtualHost = (HttpHost) iosession.getAttribute(IOSession.ATTACHMENT_KEY); + }}} + + It is often desirable to be able to react to the completion of a session request asynchronously without having to wait for it blocking the current thread of execution. One can optionally provide an implementation !SessionRequestCallback interface to get notified of events related to session requests, such as request completion, cancellation, failure or timeout. + + {{{ + ConnectingIOReactor ioreactor; + + SessionRequest sessionRequest = ioreactor.connect( + new InetSocketAddress("www.google.com", 80), null, null, + new SessionRequestCallback() { + + public void cancelled(SessionRequest request) { + } + + public void completed(SessionRequest request) { + System.out.println("new connection to " + request.getRemoteAddress()); + } + + public void failed(SessionRequest request) { + if (request.getException() != null) { + request.getException().printStackTrace(); + } + } + + public void timeout(SessionRequest request) { + } + + }); + }}} + + == I/O reactor exception handling == + + Protocol specific exceptions as well as those I/O exceptions thrown in the course of interaction with the session's channel are to be expected are to be dealt with by specific protocol handlers. These exceptions may result in termination of an individual session but should not affect the I/O reactor and all other active sessions. There are situations, however, when the I/O reactor itself encounters an internal problem such as an I/O exception in the underlying NIO classes or an unhandled runtime exception. Those types of exceptions are usually fatal and will cause the I/O reactor to shut down automatically. + + There is a possibility to override this behaviour and prevent I/O reactors from shutting down automatically in case of a runtime exception or an I/O exception in internal classes. This can be accomplished by providing a custom implementation of the !IOReactorExceptionHandler interface. + + {{{ + DefaultConnectingIOReactor ioreactor; + + ioreactor.setExceptionHandler(new IOReactorExceptionHandler() { + + public boolean handle(IOException ex) { + if (ex instanceof BindException) { + // bind failures considered OK to ignore + return true; + } + return false; - + } + + public boolean handle(RuntimeException ex) { + if (ex instanceof UnsupportedOperationException) { + // Unsupported operations considered OK to ignore + return true; + } + return false; + } + + }); + }}} + + One ought to be very careful about discarding exceptions indiscriminately. It is often much better to let the I/O reactor shut down itself cleanly and restart it rather than leaving it in an inconsistent or unstable state. + + === I/O reactor audit log === + + If an I/O reactor is unable to automatically recover from an I/O or a runtime exception it will enter the shutdown mode. First off, it will close all active listeners and cancel all pending new session requests. Then it will attempt to close all active I/O sessions gracefully giving them some time to flush pending output data and terminate cleanly. Lastly, it will forcibly shut down those I/O sessions that still remain active after the grace period. This is a fairly complex. Many things can fail at the same time and many different exceptions can be thrown in the course of the shutdown process. The I/O reactor will record all exceptions thrown during the shutdown process, including the original one that actually caused the shutdown in the first place, in an audit log. One can examine the audit log and decide whether it is safe to restart the I/O reactor. + + {{{ + DefaultConnectingIOReactor ioreactor; + + // Give it 5 sec grace period + ioreactor.shutdown(5000); + List<ExceptionEvent> events = ioreactor.getAuditLog(); + for (ExceptionEvent event: events) { + System.err.println("Time: " + event.getTimestamp()); + event.getCause().printStackTrace(); + } + }}} + == Non-blocking HTTP connections == Effectively non-blocking HTTP connections are wrappers around !IOSession with HTTP specific functionality. Non-blocking HTTP connections are stateful and not threading safe. Input / output operations on non-blocking HTTP connections should be restricted to the dispatch events triggered by the I/O event dispatch thread. @@ -1149, +1313 @@ * closed: triggered when the connection is closed. == NHTTP entities == - Producing entities; consuming entities; == NHTTP protocol handlers == --------------------------------------------------------------------- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]
