Java Reference
In-Depth Information
In the following code, a decision is made to upgrade the protocol, and the upgrade method is invoked:
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
boolean decideToUpgrade = true; // Hard coded to force the upgrade...
if (decideToUpgrade){
request.upgrade(EchoProtocolHandler.class);
}
// perform processing as normal
...
}
The HttpUpgradeHandler class in the previous example is named EchoProtocolHandler . An example
implementation of this class would look similar to the following:
public class EchoProtocolHandler implements HttpUpgradeHandler {
@Override
public void init(WebConnection wc) {
try {
ServletInputStream input = wc.getInputStream();
ServletOutputStream output = wc.getOutputStream();
ReadListener readListener = new ReadListenerImpl(input,output);
input.setReadListener(readListener);
} catch (Exception e){
System.out.println("Exception has occurred " + e);
}
}
@Override
public void destroy() {
throw new UnsupportedOperationException("Not supported yet.");
}
}
As you can see, the HttpUpgradeHandler accepts a WebConnection in the init method, and the
HttpUpgradeHandler.init passes that WebConnection automatically upon invocation. While most of the work takes
place behind the scenes, it is important to note that the upgrade process must be invoked within the code itself.
Such a solution makes sense when working with APIs such as the new WebSocket . In cases where a half-duplex
protocol is in use (see Chapter 9 for details), it would need to be upgraded to a full-duplex protocol for working with a
WebSocket .
HttpUpgradeHandler can use nonblocking I/O to complete upgrade requests.
Note
 
 
Search WWH ::




Custom Search