Start the server. @throws IOException if the socket is in use.
()
| 93 | * @throws IOException if the socket is in use. |
| 94 | */ |
| 95 | public void start() throws IOException { |
| 96 | myServerSocket = new ServerSocket(); |
| 97 | myServerSocket.bind((hostname != null) ? new InetSocketAddress(hostname, myPort) : new InetSocketAddress(myPort)); |
| 98 | |
| 99 | myThread = new Thread(new Runnable() { |
| 100 | @Override |
| 101 | public void run() { |
| 102 | do { |
| 103 | try { |
| 104 | final Socket finalAccept = myServerSocket.accept(); |
| 105 | registerConnection(finalAccept); |
| 106 | finalAccept.setSoTimeout(SOCKET_READ_TIMEOUT); |
| 107 | final InputStream inputStream = finalAccept.getInputStream(); |
| 108 | asyncRunner.exec(new Runnable() { |
| 109 | @Override |
| 110 | public void run() { |
| 111 | OutputStream outputStream = null; |
| 112 | try { |
| 113 | outputStream = finalAccept.getOutputStream(); |
| 114 | HTTPSession session = new HTTPSession(inputStream, outputStream, finalAccept.getInetAddress()); |
| 115 | while (!finalAccept.isClosed()) { |
| 116 | session.execute(); |
| 117 | } |
| 118 | } catch (Exception e) { |
| 119 | // When the socket is closed by the client, we throw our own SocketException |
| 120 | // to break the "keep alive" loop above. |
| 121 | if (!(e instanceof SocketException && "NanoHttpd Shutdown".equals(e.getMessage()))) { |
| 122 | e.printStackTrace(); |
| 123 | } |
| 124 | } finally { |
| 125 | safeClose(outputStream); |
| 126 | safeClose(inputStream); |
| 127 | safeClose(finalAccept); |
| 128 | unRegisterConnection(finalAccept); |
| 129 | } |
| 130 | } |
| 131 | }); |
| 132 | } catch (IOException e) { |
| 133 | } |
| 134 | } while (!myServerSocket.isClosed()); |
| 135 | } |
| 136 | }); |
| 137 | myThread.setDaemon(true); |
| 138 | myThread.setName("NanoHttpd Main Listener"); |
| 139 | myThread.start(); |
| 140 | } |
| 141 | |
| 142 | /** |
| 143 | * Stop the server. |
no test coverage detected