| 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.EOFException; |
| 22 | import java.io.IOException; |
| 23 | import java.net.ConnectException; |
| 24 | import java.net.InetAddress; |
| 25 | import java.net.InetSocketAddress; |
| 26 | import java.net.Socket; |
| 27 | import java.nio.ByteBuffer; |
| 28 | import java.nio.channels.NotYetConnectedException; |
| 29 | import java.nio.channels.SelectionKey; |
| 30 | import java.nio.channels.SocketChannel; |
| 31 | import java.util.List; |
| 32 | import java.util.concurrent.CopyOnWriteArrayList; |
| 33 |
| 34 | public class PyroClient { |
| 35 | private final PyroSelector selector; |
| 36 |
| 37 | private final SelectionKey key; |
| 38 |
| 39 | private final ByteStream outbound; |
| 40 |
| 41 | // called by PyroSelector.connect() |
| 42 | PyroClient(PyroSelector selector, InetSocketAddress bind, |
| 43 | InetSocketAddress host) throws IOException { |
| 44 | this(selector, PyroClient.bindAndConfigure(selector, |
| 45 | SocketChannel.open(), bind)); |
| 46 |
| 47 | ((SocketChannel) this.key.channel()).connect(host); |
| 48 | } |
| 49 |
| 50 | // called by PyroClient and PyroServer |
| 51 | PyroClient(PyroSelector selector, SelectionKey key) { |
| 52 | this.selector = selector; |
| 53 | this.selector.checkThread(); |
| 54 |
| 55 | this.key = key; |
| 56 | this.key.attach(this); |
| 57 |
| 58 | this.outbound = new ByteStream(); |
| 59 | this.listeners = new CopyOnWriteArrayList<PyroClientListener>(); |
| 60 | this.lastEventTime = System.currentTimeMillis(); |
| 61 | } |
| 62 |
| 63 | // |
| 64 |
| 65 | private final List<PyroClientListener> listeners; |
| 66 |
| 67 | public void addListener(PyroClientListener listener) { |
| 68 | this.selector.checkThread(); |
| 69 |
| 70 | this.listeners.add(listener); |
| 71 | } |
| 72 |
| 73 | public void removeListener(PyroClientListener listener) { |
| 74 | this.selector.checkThread(); |
| 75 |
| 76 | this.listeners.remove(listener); |
| 77 | } |
| 78 |
| 79 | public void removeListeners() { |
| 80 | this.selector.checkThread(); |
| 81 |
| 82 | this.listeners.clear(); |
| 83 | } |
| 84 |
| 85 | /** |
| 86 | * Returns the PyroSelector that created this client |
| 87 | */ |
| 88 |
| 89 | public PyroSelector selector() { |
| 90 | return this.selector; |
| 91 | } |
| 92 |
| 93 | // |
| 94 |
| 95 | private Object attachment; |
| 96 |
| 97 | /** |
| 98 | * Attach any object to a client, for example to store session information |
| 99 | */ |
| 100 |
| 101 | public void attach(Object attachment) { |
| 102 | this.attachment = attachment; |
| 103 | } |
| 104 |
| 105 | /** |
| 106 | * Returns the previously attached object, or <code>null</code> if none is |
| 107 | * set |
| 108 | */ |
| 109 |
| 110 | public <T> T attachment() { |
| 111 | return (T) this.attachment; |
| 112 | } |
| 113 |
| 114 | // |
| 115 |
| 116 | /** |
| 117 | * Returns the local socket address (host+port) |
| 118 | */ |
| 119 |
| 120 | public InetSocketAddress getLocalAddress() { |
| 121 | Socket s = ((SocketChannel) key.channel()).socket(); |
| 122 | return (InetSocketAddress) s.getLocalSocketAddress(); |
| 123 | } |
| 124 |
| 125 | /** |
| 126 | * Returns the remove socket address (host+port) |
| 127 | */ |
| 128 |
| 129 | public InetSocketAddress getRemoteAddress() { |
| 130 | Socket s = ((SocketChannel) key.channel()).socket(); |
| 131 | return (InetSocketAddress) s.getRemoteSocketAddress(); |
| 132 | } |
| 133 |
| 134 | // |
| 135 |
| 136 | public void setTimeout(int ms) throws IOException { |
| 137 | this.selector.checkThread(); |
| 138 |
| 139 | ((SocketChannel) key.channel()).socket().setSoTimeout(ms); |
| 140 |
| 141 | // prevent a call to setTimeout from immediately causing a timeout |
| 142 | this.lastEventTime = System.currentTimeMillis(); |
| 143 | this.timeout = ms; |
| 144 | } |
| 145 |
| 146 | public void setLinger(boolean enabled, int seconds) throws IOException { |
| 147 | this.selector.checkThread(); |
| 148 |
| 149 | ((SocketChannel) key.channel()).socket().setSoLinger(enabled, seconds); |
| 150 | } |
| 151 |
| 152 | public void setKeepAlive(boolean enabled) throws IOException { |
| 153 | this.selector.checkThread(); |
| 154 |
| 155 | ((SocketChannel) key.channel()).socket().setKeepAlive(enabled); |
| 156 | } |
| 157 |
| 158 | // |
| 159 |
| 160 | // |
| 161 |
| 162 | // |
| 163 |
| 164 | private boolean doEagerWrite = false; |
| 165 |
| 166 | /** |
| 167 | * If enabled, causes calls to write() to make an attempt to write the |
| 168 | * bytes, without waiting for the selector to signal writable state. |
| 169 | */ |
| 170 |
| 171 | public void setEagerWrite(boolean enabled) { |
| 172 | this.doEagerWrite = enabled; |
| 173 | } |
| 174 |
| 175 | // |
| 176 |
| 177 | public void writeCopy(ByteBuffer data) throws PyroException { |
| 178 | this.write(this.selector.copy(data)); |
| 179 | } |
| 180 |
| 181 | /** |
| 182 | * Will enqueue the bytes to send them<br> |
| 183 | * 1. when the selector is ready to write, if eagerWrite is disabled |
| 184 | * (default)<br> |
| 185 | * 2. immediately, if eagerWrite is enabled<br> |
| 186 | * The ByteBuffer instance is kept, not copied, and thus should not be |
| 187 | * modified |
| 188 | * |
| 189 | * @throws PyroException |
| 190 | * when shutdown() has been called. |
| 191 | */ |
| 192 |
| 193 | public void write(ByteBuffer data) throws PyroException { |
| 194 | this.selector.checkThread(); |
| 195 |
| 196 | if (!this.key.isValid()) { |
| 197 | // graceful, as this is meant to be async |
| 198 | return; |
| 199 | } |
| 200 |
| 201 | if (this.doShutdown) { |
| 202 | throw new PyroException("shutting down"); |
| 203 | } |
| 204 |
| 205 | this.outbound.append(data); |
| 206 |
| 207 | if (this.doEagerWrite) { |
| 208 | try { |
| 209 | this.onReadyToWrite(System.currentTimeMillis()); |
| 210 | } catch (NotYetConnectedException exc) { |
| 211 | this.adjustWriteOp(); |
| 212 | } catch (IOException exc) { |
| 213 | this.onConnectionError(exc); |
| 214 | key.cancel(); |
| 215 | } |
| 216 | } else { |
| 217 | this.adjustWriteOp(); |
| 218 | } |
| 219 | } |
| 220 |
| 221 | /** |
| 222 | * Writes as many as possible bytes to the socket buffer |
| 223 | */ |
| 224 |
| 225 | public int flush() { |
| 226 | int total = 0; |
| 227 |
| 228 | while (this.outbound.hasData()) { |
| 229 | int written; |
| 230 |
| 231 | try { |
| 232 | written = this.onReadyToWrite(System.currentTimeMillis()); |
| 233 | } catch (IOException exc) { |
| 234 | written = 0; |
| 235 | } |
| 236 |
| 237 | if (written == 0) { |
| 238 | break; |
| 239 | } |
| 240 |
| 241 | total += written; |
| 242 | } |
| 243 |
| 244 | return total; |
| 245 | } |
| 246 |
| 247 | /** |
| 248 | * Makes an attempt to write all outbound bytes, fails on failure. |
| 249 | * |
| 250 | * @throws PyroException |
| 251 | * on failure |
| 252 | */ |
| 253 |
| 254 | public int flushOrDie() throws PyroException { |
| 255 | int total = 0; |
| 256 |
| 257 | while (this.outbound.hasData()) { |
| 258 | int written; |
| 259 |
| 260 | try { |
| 261 | written = this.onReadyToWrite(System.currentTimeMillis()); |
| 262 | } catch (IOException exc) { |
| 263 | written = 0; |
| 264 | } |
| 265 |
| 266 | if (written == 0) { |
| 267 | throw new PyroException("failed to flush, wrote " + total |
| 268 | + " bytes"); |
| 269 | } |
| 270 |
| 271 | total += written; |
| 272 | } |
| 273 |
| 274 | return total; |
| 275 | } |
| 276 |
| 277 | /** |
| 278 | * Returns whether there are bytes left in the outbound queue. |
| 279 | */ |
| 280 |
| 281 | public boolean hasDataEnqueued() { |
| 282 | this.selector.checkThread(); |
| 283 |
| 284 | return this.outbound.hasData(); |
| 285 | } |
| 286 |
| 287 | private boolean doShutdown = false; |
| 288 |
| 289 | /** |
| 290 | * Gracefully shuts down the connection. The connection is closed after the |
| 291 | * last outbound bytes are sent. Enqueuing new bytes after shutdown, is not |
| 292 | * allowed and will throw an exception |
| 293 | */ |
| 294 |
| 295 | public void shutdown() { |
| 296 | this.selector.checkThread(); |
| 297 |
| 298 | this.doShutdown = true; |
| 299 |
| 300 | if (!this.hasDataEnqueued()) { |
| 301 | this.dropConnection(); |
| 302 | } |
| 303 | } |
| 304 |
| 305 | /** |
| 306 | * Immediately drop the connection, regardless of any pending outbound |
| 307 | * bytes. Actual behaviour depends on the socket linger settings. |
| 308 | */ |
| 309 |
| 310 | public void dropConnection() { |
| 311 | this.selector.checkThread(); |
| 312 |
| 313 | if (this.isDisconnected()) { |
| 314 | return; |
| 315 | } |
| 316 |
| 317 | Runnable drop = new Runnable() { |
| 318 | @Override |
| 319 | @SuppressWarnings("synthetic-access") |
| 320 | public void run() { |
| 321 | try { |
| 322 | if (key.channel().isOpen()) { |
| 323 | ((SocketChannel) key.channel()).close(); |
| 324 | } |
| 325 | } catch (Exception exc) { |
| 326 | selector().scheduleTask(this); |
| 327 | } |
| 328 | } |
| 329 | }; |
| 330 |
| 331 | drop.run(); |
| 332 |
| 333 | this.onConnectionError("local"); |
| 334 | } |
| 335 |
| 336 | /** |
| 337 | * Returns whether the connection is connected to a remote client. |
| 338 | */ |
| 339 |
| 340 | public boolean isDisconnected() { |
| 341 | this.selector.checkThread(); |
| 342 |
| 343 | return !((SocketChannel) this.key.channel()).isOpen(); |
| 344 | } |
| 345 |
| 346 | // |
| 347 |
| 348 | void onInterestOp(long now) { |
| 349 | if (!key.isValid()) { |
| 350 | this.onConnectionError("remote"); |
| 351 | } else { |
| 352 | try { |
| 353 | if (key.isConnectable()) |
| 354 | this.onReadyToConnect(now); |
| 355 | if (key.isReadable()) |
| 356 | this.onReadyToRead(now); |
| 357 | if (key.isWritable()) |
| 358 | this.onReadyToWrite(now); |
| 359 | } catch (Exception exc) { |
| 360 | this.onConnectionError(exc); |
| 361 | key.cancel(); |
| 362 | } |
| 363 | } |
| 364 | } |
| 365 |
| 366 | private long timeout = 0L; |
| 367 |
| 368 | private long lastEventTime; |
| 369 |
| 370 | boolean didTimeout(long now) { |
| 371 | if (this.timeout == 0) |
| 372 | return false; // never timeout |
| 373 | return (now - this.lastEventTime) > this.timeout; |
| 374 | } |
| 375 |
| 376 | private void onReadyToConnect(long now) throws IOException { |
| 377 | this.selector.checkThread(); |
| 378 | this.lastEventTime = now; |
| 379 |
| 380 | this.selector.adjustInterestOp(key, SelectionKey.OP_CONNECT, false); |
| 381 | boolean result = ((SocketChannel) key.channel()).finishConnect(); |
| 382 |
| 383 | for (PyroClientListener listener: this.listeners) |
| 384 | listener.connectedClient(this); |
| 385 | } |
| 386 |
| 387 | private void onReadyToRead(long now) throws IOException { |
| 388 | this.selector.checkThread(); |
| 389 | this.lastEventTime = now; |
| 390 |
| 391 | SocketChannel channel = (SocketChannel) key.channel(); |
| 392 |
| 393 | ByteBuffer buffer = this.selector.networkBuffer; |
| 394 |
| 395 | // read from channel |
| 396 | buffer.clear(); |
| 397 | int bytes = channel.read(buffer); |
| 398 | if (bytes == -1) |
| 399 | throw new EOFException(); |
| 400 | buffer.flip(); |
| 401 |
| 402 | for (PyroClientListener listener: this.listeners) |
| 403 | listener.receivedData(this, buffer); |
| 404 | } |
| 405 |
| 406 | private int onReadyToWrite(long now) throws IOException { |
| 407 | this.selector.checkThread(); |
| 408 | //this.lastEventTime = now; |
| 409 |
| 410 | int sent = 0; |
| 411 |
| 412 | // copy outbound bytes into network buffer |
| 413 | ByteBuffer buffer = this.selector.networkBuffer; |
| 414 | buffer.clear(); |
| 415 | this.outbound.get(buffer); |
| 416 | buffer.flip(); |
| 417 |
| 418 | // write to channel |
| 419 | if (buffer.hasRemaining()) { |
| 420 | SocketChannel channel = (SocketChannel) key.channel(); |
| 421 | sent = channel.write(buffer); |
| 422 | } |
| 423 |
| 424 | if (sent > 0) { |
| 425 | this.outbound.discard(sent); |
| 426 | } |
| 427 |
| 428 | for (PyroClientListener listener: this.listeners) |
| 429 | listener.sentData(this, sent); |
| 430 |
| 431 | this.adjustWriteOp(); |
| 432 |
| 433 | if (this.doShutdown && !this.outbound.hasData()) { |
| 434 | this.dropConnection(); |
| 435 | } |
| 436 |
| 437 | return sent; |
| 438 | } |
| 439 |
| 440 | void onConnectionError(final Object cause) { |
| 441 | this.selector.checkThread(); |
| 442 |
| 443 | try { |
| 444 | // if the key is invalid, the channel may remain open!! |
| 445 | ((SocketChannel) this.key.channel()).close(); |
| 446 | } catch (Exception exc) { |
| 447 | // type: java.io.IOException |
| 448 | // message: |
| 449 | // "A non-blocking socket operation could not be completed immediately" |
| 450 |
| 451 | // try again later |
| 452 | this.selector.scheduleTask(new Runnable() { |
| 453 | @Override |
| 454 | public void run() { |
| 455 | PyroClient.this.onConnectionError(cause); |
| 456 | } |
| 457 | }); |
| 458 |
| 459 | return; |
| 460 | } |
| 461 |
| 462 | if (cause instanceof ConnectException) { |
| 463 | for (PyroClientListener listener: this.listeners) |
| 464 | listener.unconnectableClient(this, (Exception)cause); |
| 465 | } else if (cause instanceof EOFException) // after read=-1 |
| 466 | { |
| 467 | for (PyroClientListener listener: this.listeners) |
| 468 | listener.disconnectedClient(this); |
| 469 | } else if (cause instanceof IOException) { |
| 470 | for (PyroClientListener listener: this.listeners) |
| 471 | listener.droppedClient(this, (IOException) cause); |
| 472 | } else if (!(cause instanceof String)) { |
| 473 | for (PyroClientListener listener: this.listeners) |
| 474 | listener.unconnectableClient(this, null); |
| 475 | } else if (cause.equals("local")) { |
| 476 | for (PyroClientListener listener: this.listeners) |
| 477 | listener.disconnectedClient(this); |
| 478 | } else if (cause.equals("remote")) { |
| 479 | for (PyroClientListener listener: this.listeners) |
| 480 | listener.droppedClient(this, null); |
| 481 | } else { |
| 482 | throw new IllegalStateException("illegal cause: " + cause); |
| 483 | } |
| 484 | } |
| 485 |
| 486 | public String toString() { |
| 487 | return this.getClass().getSimpleName() + "[" + this.getAddressText() |
| 488 | + "]"; |
| 489 | } |
| 490 |
| 491 | private final String getAddressText() { |
| 492 | if (!this.key.channel().isOpen()) |
| 493 | return "closed"; |
| 494 |
| 495 | InetSocketAddress sockaddr = this.getRemoteAddress(); |
| 496 | if (sockaddr == null) |
| 497 | return "connecting"; |
| 498 | InetAddress inetaddr = sockaddr.getAddress(); |
| 499 | return inetaddr.getHostAddress() + "@" + sockaddr.getPort(); |
| 500 | } |
| 501 |
| 502 | // |
| 503 |
| 504 | void adjustWriteOp() { |
| 505 | this.selector.checkThread(); |
| 506 |
| 507 | boolean interested = this.outbound.hasData(); |
| 508 |
| 509 | this.selector.adjustInterestOp(this.key, SelectionKey.OP_WRITE, |
| 510 | interested); |
| 511 | } |
| 512 |
| 513 | static final SelectionKey bindAndConfigure(PyroSelector selector, |
| 514 | SocketChannel channel, InetSocketAddress bind) throws IOException { |
| 515 | selector.checkThread(); |
| 516 |
| 517 | channel.socket().bind(bind); |
| 518 |
| 519 | return configure(selector, channel, true); |
| 520 | } |
| 521 |
| 522 | static final SelectionKey configure(PyroSelector selector, |
| 523 | SocketChannel channel, boolean connect) throws IOException { |
| 524 | selector.checkThread(); |
| 525 |
| 526 | channel.configureBlocking(false); |
| 527 | // channel.socket().setSoLinger(false, 0); // this will b0rk your |
| 528 | // connections |
| 529 | channel.socket().setSoLinger(true, 4); |
| 530 | channel.socket().setReuseAddress(false); |
| 531 | channel.socket().setKeepAlive(false); |
| 532 | channel.socket().setTcpNoDelay(true); |
| 533 | channel.socket().setReceiveBufferSize(PyroSelector.BUFFER_SIZE); |
| 534 | channel.socket().setSendBufferSize(PyroSelector.BUFFER_SIZE); |
| 535 |
| 536 | int ops = SelectionKey.OP_READ; |
| 537 | if (connect) |
| 538 | ops |= SelectionKey.OP_CONNECT; |
| 539 |
| 540 | return selector.register(channel, ops); |
| 541 | } |
| 542 | } |
| 543 |