| 6 | * |
| 7 | * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. |
| 8 | * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. |
| 9 | * Neither the name of the <ORGANIZATION> nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. |
| 10 | * |
| 11 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, |
| 12 | * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. |
| 13 | * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, |
| 14 | * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; |
| 15 | * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, |
| 16 | * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
| 17 | */ |
| 18 |
| 19 | package jawnae.pyronet; |
| 20 |
| 21 | import java.io.IOException; |
| 22 | import java.net.InetAddress; |
| 23 | import java.net.InetSocketAddress; |
| 24 | import java.net.SocketTimeoutException; |
| 25 | import java.nio.ByteBuffer; |
| 26 | import java.nio.channels.CancelledKeyException; |
| 27 | import java.nio.channels.SelectableChannel; |
| 28 | import java.nio.channels.SelectionKey; |
| 29 | import java.nio.channels.Selector; |
| 30 | import java.nio.channels.ServerSocketChannel; |
| 31 | import java.nio.channels.SocketChannel; |
| 32 | import java.util.Iterator; |
| 33 | import java.util.concurrent.BlockingQueue; |
| 34 | import java.util.concurrent.LinkedBlockingQueue; |
| 35 |
| 36 | import jawnae.pyronet.events.PyroSelectorListener; |
| 37 |
| 38 | public class PyroSelector { |
| 39 | public static boolean DO_NOT_CHECK_NETWORK_THREAD = true; |
| 40 |
| 41 | public static final int BUFFER_SIZE = 64 * 1024; |
| 42 |
| 43 | Thread networkThread; |
| 44 |
| 45 | final Selector nioSelector; |
| 46 |
| 47 | final ByteBuffer networkBuffer; |
| 48 |
| 49 | final PyroSelectorListener listener; |
| 50 |
| 51 | public PyroSelector() { |
| 52 | this(null); |
| 53 | } |
| 54 |
| 55 | public PyroSelector(PyroSelectorListener listener) { |
| 56 | this.listener = listener; |
| 57 | this.networkBuffer = ByteBuffer.allocateDirect(BUFFER_SIZE); |
| 58 |
| 59 | try { |
| 60 | this.nioSelector = Selector.open(); |
| 61 | } catch (IOException exc) { |
| 62 | throw new PyroException("Failed to open a selector?!", exc); |
| 63 | } |
| 64 |
| 65 | this.networkThread = Thread.currentThread(); |
| 66 | } |
| 67 |
| 68 | // |
| 69 |
| 70 | public ByteBuffer malloc(int size) { |
| 71 | return ByteBuffer.allocate(size); |
| 72 | } |
| 73 |
| 74 | public ByteBuffer malloc(byte[] array) { |
| 75 | ByteBuffer copy = this.malloc(array.length); |
| 76 | copy.put(array); |
| 77 | copy.flip(); |
| 78 | return copy; |
| 79 | } |
| 80 |
| 81 | public ByteBuffer copy(ByteBuffer buffer) { |
| 82 | ByteBuffer copy = this.malloc(buffer.remaining()); |
| 83 | copy.put(buffer); |
| 84 | buffer.position(buffer.position() - copy.remaining()); |
| 85 | copy.flip(); |
| 86 | return copy; |
| 87 | } |
| 88 |
| 89 | // |
| 90 |
| 91 | public final boolean isNetworkThread() { |
| 92 | if (DO_NOT_CHECK_NETWORK_THREAD) { |
| 93 | return true; |
| 94 | } |
| 95 |
| 96 | return networkThread == Thread.currentThread(); |
| 97 | } |
| 98 |
| 99 | public final Thread networkThread() { |
| 100 | return this.networkThread; |
| 101 | } |
| 102 |
| 103 | public final void checkThread() { |
| 104 | if (DO_NOT_CHECK_NETWORK_THREAD) { |
| 105 | return; |
| 106 | } |
| 107 |
| 108 | if (!this.isNetworkThread()) { |
| 109 | throw new PyroException( |
| 110 | "call from outside the network-thread, you must schedule tasks"); |
| 111 | } |
| 112 | } |
| 113 |
| 114 | public PyroServer listen(InetSocketAddress end, int backlog) |
| 115 | throws IOException { |
| 116 | try { |
| 117 | return new PyroServer(this, nioSelector, end, backlog); |
| 118 | } catch (IOException exc) { |
| 119 | if (this.listener == null) |
| 120 | throw exc; |
| 121 |
| 122 | this.listener.serverBindFailed(exc); |
| 123 | return null; |
| 124 | } |
| 125 | } |
| 126 |
| 127 | public PyroServer listen(InetSocketAddress end) throws IOException { |
| 128 | return this.listen(end, 50); |
| 129 | } |
| 130 |
| 131 | public PyroServer listen(int port) throws IOException { |
| 132 | return this.listen(new InetSocketAddress(InetAddress.getLocalHost(), |
| 133 | port)); |
| 134 | } |
| 135 |
| 136 | public PyroClient connect(InetSocketAddress host) throws IOException { |
| 137 | return this.connect(host, null); |
| 138 | } |
| 139 |
| 140 | public PyroClient connect(InetSocketAddress host, InetSocketAddress bind) |
| 141 | throws IOException { |
| 142 | try { |
| 143 | return new PyroClient(this, bind, host); |
| 144 | } catch (IOException exc) { |
| 145 | if (this.listener == null) |
| 146 | throw exc; |
| 147 |
| 148 | this.listener.clientBindFailed(exc); |
| 149 | return null; |
| 150 | } |
| 151 | } |
| 152 |
| 153 | public void select() { |
| 154 | this.select(10); |
| 155 | } |
| 156 |
| 157 | public void select(long eventTimeout) { |
| 158 | this.checkThread(); |
| 159 |
| 160 | // |
| 161 |
| 162 | this.executePendingTasks(); |
| 163 | this.performNioSelect(eventTimeout); |
| 164 |
| 165 | final long now = System.currentTimeMillis(); |
| 166 | this.handleSelectedKeys(now); |
| 167 | this.handleSocketTimeouts(now); |
| 168 | } |
| 169 |
| 170 | private void executePendingTasks() { |
| 171 | while (true) { |
| 172 | Runnable task = this.tasks.poll(); |
| 173 | if (task == null) |
| 174 | break; |
| 175 |
| 176 | if (this.listener != null) |
| 177 | this.listener.executingTask(task); |
| 178 |
| 179 | try { |
| 180 | task.run(); |
| 181 | } catch (Throwable cause) { |
| 182 | if (this.listener != null) |
| 183 | this.listener.taskCrashed(task, cause); |
| 184 | else |
| 185 | cause.printStackTrace(); |
| 186 | } |
| 187 | } |
| 188 | } |
| 189 |
| 190 | private final void performNioSelect(long timeout) { |
| 191 | int selected; |
| 192 | try { |
| 193 | selected = nioSelector.select(timeout); |
| 194 | } catch (IOException exc) { |
| 195 | if (this.listener != null) |
| 196 | this.listener.selectFailure(exc); |
| 197 | else |
| 198 | exc.printStackTrace(); |
| 199 | return; |
| 200 | } |
| 201 |
| 202 | if (this.listener != null) |
| 203 | this.listener.selectedKeys(selected); |
| 204 | } |
| 205 |
| 206 | private final void handleSelectedKeys(long now) { |
| 207 | Iterator<SelectionKey> keys = nioSelector.selectedKeys().iterator(); |
| 208 |
| 209 | while (keys.hasNext()) { |
| 210 | SelectionKey key = keys.next(); |
| 211 | keys.remove(); |
| 212 |
| 213 | if (key.channel() instanceof ServerSocketChannel) { |
| 214 | PyroServer server = (PyroServer) key.attachment(); |
| 215 | if (this.listener != null) |
| 216 | this.listener.serverSelected(server); |
| 217 | server.onInterestOp(); |
| 218 | } |
| 219 |
| 220 | if (key.channel() instanceof SocketChannel) { |
| 221 | PyroClient client = (PyroClient) key.attachment(); |
| 222 | if (this.listener != null) |
| 223 | this.listener.clientSelected(client, key.readyOps()); |
| 224 | client.onInterestOp(now); |
| 225 | } |
| 226 | } |
| 227 | } |
| 228 |
| 229 | private final void handleSocketTimeouts(long now) { |
| 230 | for (SelectionKey key: nioSelector.keys()) { |
| 231 | if (key.channel() instanceof SocketChannel) { |
| 232 | PyroClient client = (PyroClient) key.attachment(); |
| 233 |
| 234 | if (client.didTimeout(now)) { |
| 235 | try { |
| 236 | throw new SocketTimeoutException( |
| 237 | "PyroNet detected NIO timeout"); |
| 238 | } catch (SocketTimeoutException exc) { |
| 239 | client.onConnectionError(exc); |
| 240 | } |
| 241 | } |
| 242 | } |
| 243 | } |
| 244 | } |
| 245 |
| 246 | public void spawnNetworkThread(final String name) { |
| 247 | // now no thread can access this selector |
| 248 | // |
| 249 | // N.B. |
| 250 | // -- updating this non-volatile field is thread-safe |
| 251 | // -- because the current thread can see it (causing it |
| 252 | // -- to become UNACCESSIBLE), and all other threads |
| 253 | // -- that might not see the change will |
| 254 | // -- (continue to) block access to this selector |
| 255 | this.networkThread = null; |
| 256 |
| 257 | new Thread(new Runnable() { |
| 258 | @Override |
| 259 | public void run() { |
| 260 | // spawned thread can access this selector |
| 261 | // |
| 262 | // N.B. |
| 263 | // -- updating this non-volatile field is thread-safe |
| 264 | // -- because the current thread can see it (causing it |
| 265 | // -- to become ACCESSIBLE), and all other threads |
| 266 | // -- that might not see the change will |
| 267 | // -- (continue to) block access to this selector |
| 268 | PyroSelector.this.networkThread = Thread.currentThread(); |
| 269 |
| 270 | // start select-loop |
| 271 | try { |
| 272 | while (true) { |
| 273 | PyroSelector.this.select(); |
| 274 | } |
| 275 | } catch (Exception exc) { |
| 276 | // this never be caused by Pyro-code |
| 277 | throw new IllegalStateException(exc); |
| 278 | } |
| 279 | } |
| 280 | }, name).start(); |
| 281 | } |
| 282 |
| 283 | // |
| 284 |
| 285 | private BlockingQueue<Runnable> tasks = new LinkedBlockingQueue<Runnable>(); |
| 286 |
| 287 | public void scheduleTask(Runnable task) { |
| 288 | if (task == null) { |
| 289 | throw new NullPointerException(); |
| 290 | } |
| 291 |
| 292 | try { |
| 293 | this.tasks.put(task); |
| 294 | } catch (InterruptedException e) { |
| 295 | throw new RuntimeException(e); |
| 296 | } |
| 297 | wakeup(); |
| 298 | } |
| 299 |
| 300 | public void wakeup() { |
| 301 | this.nioSelector.wakeup(); |
| 302 | } |
| 303 |
| 304 | // |
| 305 |
| 306 | final SelectionKey register(SelectableChannel channel, int ops) |
| 307 | throws IOException { |
| 308 | return channel.register(this.nioSelector, ops); |
| 309 | } |
| 310 |
| 311 | final boolean adjustInterestOp(SelectionKey key, int op, boolean state) { |
| 312 | this.checkThread(); |
| 313 |
| 314 | try { |
| 315 | int ops = key.interestOps(); |
| 316 | boolean changed = state != ((ops & op) == op); |
| 317 | if (changed) |
| 318 | key.interestOps(state ? (ops | op) : (ops & ~op)); |
| 319 | return changed; |
| 320 | } catch (CancelledKeyException exc) { |
| 321 | // ignore |
| 322 | return false; |
| 323 | } |
| 324 | } |
| 325 | } |
| 326 |