| 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.InetSocketAddress; |
| 23 | import java.net.SocketTimeoutException; |
| 24 | import java.nio.ByteBuffer; |
| 25 | import java.nio.channels.CancelledKeyException; |
| 26 | import java.nio.channels.SelectableChannel; |
| 27 | import java.nio.channels.SelectionKey; |
| 28 | import java.nio.channels.Selector; |
| 29 | import java.nio.channels.SocketChannel; |
| 30 | import java.util.Iterator; |
| 31 | import java.util.concurrent.BlockingQueue; |
| 32 | import java.util.concurrent.LinkedBlockingQueue; |
| 33 |
| 34 | public class PyroSelector { |
| 35 | public static boolean DO_NOT_CHECK_NETWORK_THREAD = true; |
| 36 |
| 37 | public static final int BUFFER_SIZE = 64 * 1024; |
| 38 |
| 39 | Thread networkThread; |
| 40 |
| 41 | final Selector nioSelector; |
| 42 |
| 43 | final ByteBuffer networkBuffer; |
| 44 |
| 45 | public PyroSelector() { |
| 46 | this.networkBuffer = ByteBuffer.allocateDirect(BUFFER_SIZE); |
| 47 |
| 48 | try { |
| 49 | this.nioSelector = Selector.open(); |
| 50 | } catch (IOException exc) { |
| 51 | throw new PyroException("Failed to open a selector?!", exc); |
| 52 | } |
| 53 |
| 54 | this.networkThread = Thread.currentThread(); |
| 55 | } |
| 56 |
| 57 | // |
| 58 |
| 59 | public ByteBuffer malloc(int size) { |
| 60 | return ByteBuffer.allocate(size); |
| 61 | } |
| 62 |
| 63 | public ByteBuffer malloc(byte[] array) { |
| 64 | ByteBuffer copy = this.malloc(array.length); |
| 65 | copy.put(array); |
| 66 | copy.flip(); |
| 67 | return copy; |
| 68 | } |
| 69 |
| 70 | public ByteBuffer copy(ByteBuffer buffer) { |
| 71 | ByteBuffer copy = this.malloc(buffer.remaining()); |
| 72 | copy.put(buffer); |
| 73 | buffer.position(buffer.position() - copy.remaining()); |
| 74 | copy.flip(); |
| 75 | return copy; |
| 76 | } |
| 77 |
| 78 | // |
| 79 |
| 80 | public final boolean isNetworkThread() { |
| 81 | if (DO_NOT_CHECK_NETWORK_THREAD) { |
| 82 | return true; |
| 83 | } |
| 84 |
| 85 | return networkThread == Thread.currentThread(); |
| 86 | } |
| 87 |
| 88 | public final Thread networkThread() { |
| 89 | return this.networkThread; |
| 90 | } |
| 91 |
| 92 | public final void checkThread() { |
| 93 | if (DO_NOT_CHECK_NETWORK_THREAD) { |
| 94 | return; |
| 95 | } |
| 96 |
| 97 | if (!this.isNetworkThread()) { |
| 98 | throw new PyroException( |
| 99 | "call from outside the network-thread, you must schedule tasks"); |
| 100 | } |
| 101 | } |
| 102 |
| 103 | public PyroClient connect(InetSocketAddress host) throws IOException { |
| 104 | return this.connect(host, null); |
| 105 | } |
| 106 |
| 107 | public PyroClient connect(InetSocketAddress host, InetSocketAddress bind) |
| 108 | throws IOException { |
| 109 | try { |
| 110 | return new PyroClient(this, bind, host); |
| 111 | } catch (IOException exc) { |
| 112 | throw exc; |
| 113 | } |
| 114 | } |
| 115 |
| 116 | public void select() { |
| 117 | this.select(10); |
| 118 | } |
| 119 |
| 120 | public void select(long eventTimeout) { |
| 121 | this.checkThread(); |
| 122 |
| 123 | // |
| 124 |
| 125 | this.executePendingTasks(); |
| 126 | this.performNioSelect(eventTimeout); |
| 127 |
| 128 | final long now = System.currentTimeMillis(); |
| 129 | this.handleSelectedKeys(now); |
| 130 | this.handleSocketTimeouts(now); |
| 131 | } |
| 132 |
| 133 | private void executePendingTasks() { |
| 134 | while (true) { |
| 135 | Runnable task = this.tasks.poll(); |
| 136 | if (task == null) |
| 137 | break; |
| 138 |
| 139 | try { |
| 140 | task.run(); |
| 141 | } catch (Throwable cause) { |
| 142 | cause.printStackTrace(); |
| 143 | } |
| 144 | } |
| 145 | } |
| 146 |
| 147 | private final void performNioSelect(long timeout) { |
| 148 | int selected; |
| 149 | try { |
| 150 | selected = nioSelector.select(timeout); |
| 151 | } catch (IOException exc) { |
| 152 | exc.printStackTrace(); |
| 153 | return; |
| 154 | } |
| 155 | } |
| 156 |
| 157 | private final void handleSelectedKeys(long now) { |
| 158 | Iterator<SelectionKey> keys = nioSelector.selectedKeys().iterator(); |
| 159 |
| 160 | while (keys.hasNext()) { |
| 161 | SelectionKey key = keys.next(); |
| 162 | keys.remove(); |
| 163 |
| 164 | if (key.channel() instanceof SocketChannel) { |
| 165 | PyroClient client = (PyroClient) key.attachment(); |
| 166 | client.onInterestOp(now); |
| 167 | } |
| 168 | } |
| 169 | } |
| 170 |
| 171 | private final void handleSocketTimeouts(long now) { |
| 172 | for (SelectionKey key: nioSelector.keys()) { |
| 173 | if (key.channel() instanceof SocketChannel) { |
| 174 | PyroClient client = (PyroClient) key.attachment(); |
| 175 |
| 176 | if (client.didTimeout(now)) { |
| 177 | try { |
| 178 | throw new SocketTimeoutException( |
| 179 | "PyroNet detected NIO timeout"); |
| 180 | } catch (SocketTimeoutException exc) { |
| 181 | client.onConnectionError(exc); |
| 182 | } |
| 183 | } |
| 184 | } |
| 185 | } |
| 186 | } |
| 187 |
| 188 | public void spawnNetworkThread(final String name) { |
| 189 | // now no thread can access this selector |
| 190 | // |
| 191 | // N.B. |
| 192 | // -- updating this non-volatile field is thread-safe |
| 193 | // -- because the current thread can see it (causing it |
| 194 | // -- to become UNACCESSIBLE), and all other threads |
| 195 | // -- that might not see the change will |
| 196 | // -- (continue to) block access to this selector |
| 197 | this.networkThread = null; |
| 198 |
| 199 | new Thread(new Runnable() { |
| 200 | @Override |
| 201 | public void run() { |
| 202 | // spawned thread can access this selector |
| 203 | // |
| 204 | // N.B. |
| 205 | // -- updating this non-volatile field is thread-safe |
| 206 | // -- because the current thread can see it (causing it |
| 207 | // -- to become ACCESSIBLE), and all other threads |
| 208 | // -- that might not see the change will |
| 209 | // -- (continue to) block access to this selector |
| 210 | PyroSelector.this.networkThread = Thread.currentThread(); |
| 211 |
| 212 | // start select-loop |
| 213 | try { |
| 214 | while (true) { |
| 215 | PyroSelector.this.select(); |
| 216 | } |
| 217 | } catch (Exception exc) { |
| 218 | // this never be caused by Pyro-code |
| 219 | throw new IllegalStateException(exc); |
| 220 | } |
| 221 | } |
| 222 | }, name).start(); |
| 223 | } |
| 224 |
| 225 | // |
| 226 |
| 227 | private BlockingQueue<Runnable> tasks = new LinkedBlockingQueue<Runnable>(); |
| 228 |
| 229 | public void scheduleTask(Runnable task) { |
| 230 | if (task == null) { |
| 231 | throw new NullPointerException(); |
| 232 | } |
| 233 |
| 234 | try { |
| 235 | this.tasks.put(task); |
| 236 | } catch (InterruptedException e) { |
| 237 | throw new RuntimeException(e); |
| 238 | } |
| 239 | wakeup(); |
| 240 | } |
| 241 |
| 242 | public void wakeup() { |
| 243 | this.nioSelector.wakeup(); |
| 244 | } |
| 245 |
| 246 | // |
| 247 |
| 248 | final SelectionKey register(SelectableChannel channel, int ops) |
| 249 | throws IOException { |
| 250 | return channel.register(this.nioSelector, ops); |
| 251 | } |
| 252 |
| 253 | final boolean adjustInterestOp(SelectionKey key, int op, boolean state) { |
| 254 | this.checkThread(); |
| 255 |
| 256 | try { |
| 257 | int ops = key.interestOps(); |
| 258 | boolean changed = state != ((ops & op) == op); |
| 259 | if (changed) |
| 260 | key.interestOps(state ? (ops | op) : (ops & ~op)); |
| 261 | return changed; |
| 262 | } catch (CancelledKeyException exc) { |
| 263 | // ignore |
| 264 | return false; |
| 265 | } |
| 266 | } |
| 267 | } |
| 268 |