| 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 | public final boolean isNetworkThread() { |
| 79 | return DO_NOT_CHECK_NETWORK_THREAD || networkThread == Thread.currentThread(); |
| 80 | } |
| 81 |
| 82 | public final Thread networkThread() { |
| 83 | return this.networkThread; |
| 84 | } |
| 85 |
| 86 | public final void checkThread() { |
| 87 | if (DO_NOT_CHECK_NETWORK_THREAD) { |
| 88 | return; |
| 89 | } |
| 90 |
| 91 | if (!this.isNetworkThread()) { |
| 92 | throw new PyroException("call from outside the network-thread, you must schedule tasks"); |
| 93 | } |
| 94 | } |
| 95 |
| 96 | public PyroClient connect(InetSocketAddress host) throws IOException { |
| 97 | return this.connect(host, null); |
| 98 | } |
| 99 |
| 100 | public PyroClient connect(InetSocketAddress host, InetSocketAddress bind) throws IOException { |
| 101 | return new PyroClient(this, bind, host); |
| 102 | } |
| 103 |
| 104 | public void select() { |
| 105 | this.select(10); |
| 106 | } |
| 107 |
| 108 | public void select(long eventTimeout) { |
| 109 | this.checkThread(); |
| 110 |
| 111 | // |
| 112 |
| 113 | this.executePendingTasks(); |
| 114 | this.performNioSelect(eventTimeout); |
| 115 |
| 116 | final long now = System.currentTimeMillis(); |
| 117 | this.handleSelectedKeys(now); |
| 118 | this.handleSocketTimeouts(now); |
| 119 | } |
| 120 |
| 121 | private void executePendingTasks() { |
| 122 | while (true) { |
| 123 | Runnable task = this.tasks.poll(); |
| 124 | if (task == null) |
| 125 | break; |
| 126 |
| 127 | try { |
| 128 | task.run(); |
| 129 | } catch (Throwable cause) { |
| 130 | cause.printStackTrace(); |
| 131 | } |
| 132 | } |
| 133 | } |
| 134 |
| 135 | private void performNioSelect(long timeout) { |
| 136 | int selected; |
| 137 | try { |
| 138 | selected = nioSelector.select(timeout); |
| 139 | } catch (IOException exc) { |
| 140 | exc.printStackTrace(); |
| 141 | } |
| 142 | } |
| 143 |
| 144 | private void handleSelectedKeys(long now) { |
| 145 | Iterator<SelectionKey> keys = nioSelector.selectedKeys().iterator(); |
| 146 |
| 147 | while (keys.hasNext()) { |
| 148 | SelectionKey key = keys.next(); |
| 149 | keys.remove(); |
| 150 |
| 151 | if (key.channel() instanceof SocketChannel) { |
| 152 | PyroClient client = (PyroClient) key.attachment(); |
| 153 | client.onInterestOp(now); |
| 154 | } |
| 155 | } |
| 156 | } |
| 157 |
| 158 | private void handleSocketTimeouts(long now) { |
| 159 | for (SelectionKey key: nioSelector.keys()) { |
| 160 | if (key.channel() instanceof SocketChannel) { |
| 161 | PyroClient client = (PyroClient) key.attachment(); |
| 162 |
| 163 | if (client.didTimeout(now)) { |
| 164 | try { |
| 165 | throw new SocketTimeoutException( |
| 166 | "PyroNet detected NIO timeout"); |
| 167 | } catch (SocketTimeoutException exc) { |
| 168 | client.onConnectionError(exc); |
| 169 | } |
| 170 | } |
| 171 | } |
| 172 | } |
| 173 | } |
| 174 |
| 175 | public void spawnNetworkThread(final String name) { |
| 176 | // now no thread can access this selector |
| 177 | // |
| 178 | // N.B. |
| 179 | // -- updating this non-volatile field is thread-safe |
| 180 | // -- because the current thread can see it (causing it |
| 181 | // -- to become UNACCESSIBLE), and all other threads |
| 182 | // -- that might not see the change will |
| 183 | // -- (continue to) block access to this selector |
| 184 | this.networkThread = null; |
| 185 |
| 186 | new Thread(new Runnable() { |
| 187 | @Override |
| 188 | public void run() { |
| 189 | // spawned 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 ACCESSIBLE), and all other threads |
| 195 | // -- that might not see the change will |
| 196 | // -- (continue to) block access to this selector |
| 197 | PyroSelector.this.networkThread = Thread.currentThread(); |
| 198 |
| 199 | // start select-loop |
| 200 | try { |
| 201 | while (true) { |
| 202 | PyroSelector.this.select(); |
| 203 | } |
| 204 | } catch (Exception exc) { |
| 205 | // this never be caused by Pyro-code |
| 206 | throw new IllegalStateException(exc); |
| 207 | } |
| 208 | } |
| 209 | }, name).start(); |
| 210 | } |
| 211 |
| 212 | // |
| 213 |
| 214 | private BlockingQueue<Runnable> tasks = new LinkedBlockingQueue<Runnable>(); |
| 215 |
| 216 | public void scheduleTask(Runnable task) { |
| 217 | if (task == null) { |
| 218 | throw new NullPointerException(); |
| 219 | } |
| 220 |
| 221 | try { |
| 222 | this.tasks.put(task); |
| 223 | } catch (InterruptedException e) { |
| 224 | throw new RuntimeException(e); |
| 225 | } |
| 226 | wakeup(); |
| 227 | } |
| 228 |
| 229 | public void wakeup() { |
| 230 | this.nioSelector.wakeup(); |
| 231 | } |
| 232 |
| 233 | // |
| 234 |
| 235 | final SelectionKey register(SelectableChannel channel, int ops) |
| 236 | throws IOException { |
| 237 | return channel.register(this.nioSelector, ops); |
| 238 | } |
| 239 |
| 240 | final boolean adjustInterestOp(SelectionKey key, int op, boolean state) { |
| 241 | this.checkThread(); |
| 242 |
| 243 | try { |
| 244 | int ops = key.interestOps(); |
| 245 | boolean changed = state != ((ops & op) == op); |
| 246 | if (changed) |
| 247 | key.interestOps(state ? (ops | op) : (ops & ~op)); |
| 248 | return changed; |
| 249 | } catch (CancelledKeyException exc) { |
| 250 | // ignore |
| 251 | return false; |
| 252 | } |
| 253 | } |
| 254 | } |
| 255 |