A simple, tiny, nicely embeddable HTTP server in Java NanoHTTPD Copyright (c) 2012-2013 by Paul S. Hawke, 2001,2005-2013 by Jarno Elonen, 2010 by Konstantinos Togias Features + limitations: Only one Java file Java 5 compatible Rele
| 152 | * licence) |
| 153 | */ |
| 154 | public abstract class NanoHTTPD { |
| 155 | |
| 156 | /** |
| 157 | * Pluggable strategy for asynchronously executing requests. |
| 158 | */ |
| 159 | public interface AsyncRunner { |
| 160 | |
| 161 | void closeAll(); |
| 162 | |
| 163 | void closed(ClientHandler clientHandler); |
| 164 | |
| 165 | void exec(ClientHandler code); |
| 166 | } |
| 167 | |
| 168 | /** |
| 169 | * The runnable that will be used for every new client connection. |
| 170 | */ |
| 171 | public class ClientHandler implements Runnable { |
| 172 | |
| 173 | private final InputStream inputStream; |
| 174 | |
| 175 | private final Socket acceptSocket; |
| 176 | |
| 177 | public ClientHandler() { |
| 178 | this.inputStream = null; |
| 179 | this.acceptSocket = null; |
| 180 | } |
| 181 | |
| 182 | public ClientHandler(InputStream inputStream, Socket acceptSocket) { |
| 183 | this.inputStream = inputStream; |
| 184 | this.acceptSocket = acceptSocket; |
| 185 | } |
| 186 | |
| 187 | public void close() { |
| 188 | safeClose(this.inputStream); |
| 189 | safeClose(this.acceptSocket); |
| 190 | } |
| 191 | |
| 192 | @Override |
| 193 | public void run() { |
| 194 | OutputStream outputStream = null; |
| 195 | try { |
| 196 | outputStream = this.acceptSocket.getOutputStream(); |
| 197 | TempFileManager tempFileManager = NanoHTTPD.this.tempFileManagerFactory.create(); |
| 198 | HTTPSession session = new HTTPSession(tempFileManager, this.inputStream, outputStream, this.acceptSocket.getInetAddress()); |
| 199 | while (!this.acceptSocket.isClosed()) { |
| 200 | session.execute(); |
| 201 | } |
| 202 | } catch (Exception e) { |
| 203 | // When the socket is closed by the client, |
| 204 | // we throw our own SocketException |
| 205 | // to break the "keep alive" loop above. If |
| 206 | // the exception was anything other |
| 207 | // than the expected SocketException OR a |
| 208 | // SocketTimeoutException, print the |
| 209 | // stacktrace |
| 210 | if (!(e instanceof SocketException && "NanoHttpd Shutdown".equals(e.getMessage())) && !(e instanceof SocketTimeoutException)) { |
| 211 | NanoHTTPD.LOG.log(Level.SEVERE, "Communication with the client broken, or an bug in the handler code", e); |