package servlet;

import java.io.*;
import java.net.*;
import com.mortbay.HTTP.*;
import com.mortbay.Util.*;

/**
 * A Nagle-less version of the Jetty HttpListener, to avoid timer delays
 * that make it hard to measure HTTP performance characteristics.
 *
 * <p>Nagle's algorithm causes a packet send to be delayed by some time,
 * in the hopes that another write will come along soon enough to
 * be grouped into the same packet. Oddly, that delay appears even
 * when using sockets connected to the localhost. In either case, it
 * interferes with measurements where we want the bottleneck resource
 * to be fully utilized.
 *
 * <p>In a production system, one might not want to use a NaglessListener
 * since Nagle's algorithm can reduce wasteful network overhead. As long
 * as the application code is properly buffering its output, however,
 * such waste should not be a problem.
 */
public class NaglessListener
	extends HttpListener {

	/**
	 * Create an HTTP listener.
	 */
	public NaglessListener(InetAddrPort addrPort, HttpServer httpServer,
		int minThreads, int maxThreads, int maxIdleTimeMs)
		throws IOException {
		super(addrPort, httpServer, minThreads, maxThreads, maxIdleTimeMs);
	}

	/**
	 * The only interesting thing this class does is in this method.
	 * When the listener accepts on a socket,
	 * this method sets the TcpNoDelay option to true (turns off Nagle's
	 * algorithm) before passing the socket on to other handlers to
	 * process the request arriving on it.
	 */
	protected Socket accept(ServerSocket serverSocket)
		throws java.io.IOException {
		Socket socket = super.accept(serverSocket);
			// Java's super is being stupid
		socket.setTcpNoDelay(true);
		return socket;
	}
}
