Server Interface #
First, an interface of server.
public interface Server extends AutoCloseable {
/**
* Start the server.
*/
void start();
}
Note that Server interface extends AutoCloseable, so that it’s able to use Java try-with clause
try (Server server = new BioServer("localhost", 3128)) {
server.start();
} catch (Exception e) {
e.printStackTrace();
}
BioServer #
This is a simple implementation, using ServerSocket.
the start method will loop forever
public void start() {
try {
serverSocket = new ServerSocket();
serverSocket.bind(new InetSocketAddress(host, port));
while (true) {
Socket socket = serverSocket.accept();
process(socket);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
and the request will be processed by RequestProcessor, so that Server code will be simple and clean.