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