public interface HttpService
{
void handleRequest( HttpServiceContext context ) throws Exception;
void start();
void stop();
}
/** 同步处理的例子 */
public void handleRequest( HttpServiceContext context ) throws Exception {
MutableHttpResponse response = new DefaultHttpResponse();
StringWriter buf = new StringWriter();
PrintWriter writer = new PrintWriter(buf);
writer.println("test");
writer.flush();
IoBuffer bb = IoBuffer.allocate(1024);
bb.setAutoExpand(true);
bb.putString(buf.toString(), Charset.forName("UTF-8").newEncoder());
bb.flip();
response.setContent(bb);
response.setHeader("Pragma", "no-cache");
response.setHeader("Cache-Control", "no-cache");
response.setStatus(HttpResponseStatus.OK);
context.commitResponse(response);
}
/** 异步处理的例子,可以不马上返回,但是必须一次返回 */
public void handleRequest( HttpServiceContext context ) throws Exception {
context.addClientListener( new HttpClientListener() {
public void clientDisconnected( HttpServiceContext ctx ) {
}
public void clientIdle( HttpServiceContext ctx, long idleTime, int idleCount ) {
// do something...
// context.commitResponse(...)
}
});
}
public class ForeverFrameJettyServlet extends HttpServlet {
public void service(HttpServletRequest req, HttpServletResponse resp) throws IOException {
// handle the time request
if (req.getRequestURI().endsWith("/time")) {
// get the jetty continuation
Continuation cc = ContinuationSupport.getContinuation(req, null);
// set the header
resp.setContentType("text/html");
// write time periodically
while (true) {
cc.suspend(1000); // suspend the response
resp.getWriter().println("test");
resp.getWriter().flush();
}
}
// ...
}
}