1 /*
   2  * Copyright (c) 2000, 2009, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package java.nio.channels;
  27 
  28 import java.io.IOException;
  29 import java.net.Socket;
  30 import java.net.SocketOption;
  31 import java.net.SocketAddress;
  32 import java.nio.ByteBuffer;
  33 import java.nio.channels.spi.AbstractSelectableChannel;
  34 import java.nio.channels.spi.SelectorProvider;
  35 
  36 /**
  37  * A selectable channel for stream-oriented connecting sockets.
  38  *
  39  * <p> A socket channel is created by invoking one of the {@link #open open}
  40  * methods of this class.  It is not possible to create a channel for an arbitrary,
  41  * pre-existing socket. A newly-created socket channel is open but not yet
  42  * connected.  An attempt to invoke an I/O operation upon an unconnected
  43  * channel will cause a {@link NotYetConnectedException} to be thrown.  A
  44  * socket channel can be connected by invoking its {@link #connect connect}
  45  * method; once connected, a socket channel remains connected until it is
  46  * closed.  Whether or not a socket channel is connected may be determined by
  47  * invoking its {@link #isConnected isConnected} method.
  48  *
  49  * <p> Socket channels support <i>non-blocking connection:</i>&nbsp;A socket
  50  * channel may be created and the process of establishing the link to the
  51  * remote socket may be initiated via the {@link #connect connect} method for
  52  * later completion by the {@link #finishConnect finishConnect} method.
  53  * Whether or not a connection operation is in progress may be determined by
  54  * invoking the {@link #isConnectionPending isConnectionPending} method.
  55  *
  56  * <p> Socket channels support <i>asynchronous shutdown,</i> which is similar
  57  * to the asynchronous close operation specified in the {@link Channel} class.
  58  * If the input side of a socket is shut down by one thread while another
  59  * thread is blocked in a read operation on the socket's channel, then the read
  60  * operation in the blocked thread will complete without reading any bytes and
  61  * will return <tt>-1</tt>.  If the output side of a socket is shut down by one
  62  * thread while another thread is blocked in a write operation on the socket's
  63  * channel, then the blocked thread will receive an {@link
  64  * AsynchronousCloseException}.
  65  *
  66  * <p> Socket options are configured using the {@link #setOption(SocketOption,Object)
  67  * setOption} method. Socket channels support the following options:
  68  * <blockquote>
  69  * <table border>
  70  *   <tr>
  71  *     <th>Option Name</th>
  72  *     <th>Description</th>
  73  *   </tr>
  74  *   <tr>
  75  *     <td> {@link java.net.StandardSocketOption#SO_SNDBUF SO_SNDBUF} </td>
  76  *     <td> The size of the socket send buffer </td>
  77  *   </tr>
  78  *   <tr>
  79  *     <td> {@link java.net.StandardSocketOption#SO_RCVBUF SO_RCVBUF} </td>
  80  *     <td> The size of the socket receive buffer </td>
  81  *   </tr>
  82  *   <tr>
  83  *     <td> {@link java.net.StandardSocketOption#SO_KEEPALIVE SO_KEEPALIVE} </td>
  84  *     <td> Keep connection alive </td>
  85  *   </tr>
  86  *   <tr>
  87  *     <td> {@link java.net.StandardSocketOption#SO_REUSEADDR SO_REUSEADDR} </td>
  88  *     <td> Re-use address </td>
  89  *   </tr>
  90  *   <tr>
  91  *     <td> {@link java.net.StandardSocketOption#SO_LINGER SO_LINGER} </td>
  92  *     <td> Linger on close if data is present (when configured in blocking mode
  93  *          only) </td>
  94  *   </tr>
  95  *   <tr>
  96  *     <td> {@link java.net.StandardSocketOption#TCP_NODELAY TCP_NODELAY} </td>
  97  *     <td> Disable the Nagle algorithm </td>
  98  *   </tr>
  99  * </table>
 100  * </blockquote>
 101  * Additional (implementation specific) options may also be supported.
 102  *
 103  * <p> Socket channels are safe for use by multiple concurrent threads.  They
 104  * support concurrent reading and writing, though at most one thread may be
 105  * reading and at most one thread may be writing at any given time.  The {@link
 106  * #connect connect} and {@link #finishConnect finishConnect} methods are
 107  * mutually synchronized against each other, and an attempt to initiate a read
 108  * or write operation while an invocation of one of these methods is in
 109  * progress will block until that invocation is complete.  </p>
 110  *
 111  * @author Mark Reinhold
 112  * @author JSR-51 Expert Group
 113  * @since 1.4
 114  */
 115 
 116 public abstract class SocketChannel
 117     extends AbstractSelectableChannel
 118     implements ByteChannel, ScatteringByteChannel, GatheringByteChannel, NetworkChannel
 119 {
 120 
 121     /**
 122      * Initializes a new instance of this class.
 123      */
 124     protected SocketChannel(SelectorProvider provider) {
 125         super(provider);
 126     }
 127 
 128     /**
 129      * Opens a socket channel.
 130      *
 131      * <p> The new channel is created by invoking the {@link
 132      * java.nio.channels.spi.SelectorProvider#openSocketChannel
 133      * openSocketChannel} method of the system-wide default {@link
 134      * java.nio.channels.spi.SelectorProvider} object.  </p>
 135      *
 136      * @return  A new socket channel
 137      *
 138      * @throws  IOException
 139      *          If an I/O error occurs
 140      */
 141     public static SocketChannel open() throws IOException {
 142         return SelectorProvider.provider().openSocketChannel();
 143     }
 144 
 145     /**
 146      * Opens a socket channel and connects it to a remote address.
 147      *
 148      * <p> This convenience method works as if by invoking the {@link #open()}
 149      * method, invoking the {@link #connect(SocketAddress) connect} method upon
 150      * the resulting socket channel, passing it <tt>remote</tt>, and then
 151      * returning that channel.  </p>
 152      *
 153      * @param  remote
 154      *         The remote address to which the new channel is to be connected
 155      *
 156      * @throws  AsynchronousCloseException
 157      *          If another thread closes this channel
 158      *          while the connect operation is in progress
 159      *
 160      * @throws  ClosedByInterruptException
 161      *          If another thread interrupts the current thread
 162      *          while the connect operation is in progress, thereby
 163      *          closing the channel and setting the current thread's
 164      *          interrupt status
 165      *
 166      * @throws  UnresolvedAddressException
 167      *          If the given remote address is not fully resolved
 168      *
 169      * @throws  UnsupportedAddressTypeException
 170      *          If the type of the given remote address is not supported
 171      *
 172      * @throws  SecurityException
 173      *          If a security manager has been installed
 174      *          and it does not permit access to the given remote endpoint
 175      *
 176      * @throws  IOException
 177      *          If some other I/O error occurs
 178      */
 179     public static SocketChannel open(SocketAddress remote)
 180         throws IOException
 181     {
 182         SocketChannel sc = open();
 183         try {
 184             sc.connect(remote);
 185         } catch (Throwable x) {
 186             try {
 187                 sc.close();
 188             } catch (Throwable suppressed) {
 189                 x.addSuppressed(suppressed);
 190             }
 191             throw x;
 192         }
 193         assert sc.isConnected();
 194         return sc;
 195     }
 196 
 197     /**
 198      * Returns an operation set identifying this channel's supported
 199      * operations.
 200      *
 201      * <p> Socket channels support connecting, reading, and writing, so this
 202      * method returns <tt>(</tt>{@link SelectionKey#OP_CONNECT}
 203      * <tt>|</tt>&nbsp;{@link SelectionKey#OP_READ} <tt>|</tt>&nbsp;{@link
 204      * SelectionKey#OP_WRITE}<tt>)</tt>.  </p>
 205      *
 206      * @return  The valid-operation set
 207      */
 208     public final int validOps() {
 209         return (SelectionKey.OP_READ
 210                 | SelectionKey.OP_WRITE
 211                 | SelectionKey.OP_CONNECT);
 212     }
 213 
 214 
 215     // -- Socket-specific operations --
 216 
 217     /**
 218      * @throws  ConnectionPendingException
 219      *          If a non-blocking connect operation is already in progress on
 220      *          this channel
 221      * @throws  AlreadyBoundException               {@inheritDoc}
 222      * @throws  UnsupportedAddressTypeException     {@inheritDoc}
 223      * @throws  ClosedChannelException              {@inheritDoc}
 224      * @throws  IOException                         {@inheritDoc}
 225      *
 226      * @since 1.7
 227      */
 228     @Override
 229     public abstract SocketChannel bind(SocketAddress local)
 230         throws IOException;
 231 
 232     /**
 233      * @throws  UnsupportedOperationException           {@inheritDoc}
 234      * @throws  IllegalArgumentException                {@inheritDoc}
 235      * @throws  ClosedChannelException                  {@inheritDoc}
 236      * @throws  IOException                             {@inheritDoc}
 237      *
 238      * @since 1.7
 239      */
 240     @Override
 241     public abstract <T> SocketChannel setOption(SocketOption<T> name, T value)
 242         throws IOException;
 243 
 244     /**
 245      * Shutdown the connection for reading without closing the channel.
 246      *
 247      * <p> Once shutdown for reading then further reads on the channel will
 248      * return {@code -1}, the end-of-stream indication. If the input side of the
 249      * connection is already shutdown then invoking this method has no effect.
 250      *
 251      * @return  The channel
 252      *
 253      * @throws  NotYetConnectedException
 254      *          If this channel is not yet connected
 255      * @throws  ClosedChannelException
 256      *          If this channel is closed
 257      * @throws  IOException
 258      *          If some other I/O error occurs
 259      *
 260      * @since 1.7
 261      */
 262     public abstract SocketChannel shutdownInput() throws IOException;
 263 
 264     /**
 265      * Shutdown the connection for writing without closing the channel.
 266      *
 267      * <p> Once shutdown for writing then further attempts to write to the
 268      * channel will throw {@link ClosedChannelException}. If the output side of
 269      * the connection is already shutdown then invoking this method has no
 270      * effect.
 271      *
 272      * @return  The channel
 273      *
 274      * @throws  NotYetConnectedException
 275      *          If this channel is not yet connected
 276      * @throws  ClosedChannelException
 277      *          If this channel is closed
 278      * @throws  IOException
 279      *          If some other I/O error occurs
 280      *
 281      * @since 1.7
 282      */
 283     public abstract SocketChannel shutdownOutput() throws IOException;
 284 
 285     /**
 286      * Retrieves a socket associated with this channel.
 287      *
 288      * <p> The returned object will not declare any public methods that are not
 289      * declared in the {@link java.net.Socket} class.  </p>
 290      *
 291      * @return  A socket associated with this channel
 292      */
 293     public abstract Socket socket();
 294 
 295     /**
 296      * Tells whether or not this channel's network socket is connected.
 297      *
 298      * @return  <tt>true</tt> if, and only if, this channel's network socket
 299      *          is {@link #isOpen open} and connected
 300      */
 301     public abstract boolean isConnected();
 302 
 303     /**
 304      * Tells whether or not a connection operation is in progress on this
 305      * channel.  </p>
 306      *
 307      * @return  <tt>true</tt> if, and only if, a connection operation has been
 308      *          initiated on this channel but not yet completed by invoking the
 309      *          {@link #finishConnect finishConnect} method
 310      */
 311     public abstract boolean isConnectionPending();
 312 
 313     /**
 314      * Connects this channel's socket.
 315      *
 316      * <p> If this channel is in non-blocking mode then an invocation of this
 317      * method initiates a non-blocking connection operation.  If the connection
 318      * is established immediately, as can happen with a local connection, then
 319      * this method returns <tt>true</tt>.  Otherwise this method returns
 320      * <tt>false</tt> and the connection operation must later be completed by
 321      * invoking the {@link #finishConnect finishConnect} method.
 322      *
 323      * <p> If this channel is in blocking mode then an invocation of this
 324      * method will block until the connection is established or an I/O error
 325      * occurs.
 326      *
 327      * <p> This method performs exactly the same security checks as the {@link
 328      * java.net.Socket} class.  That is, if a security manager has been
 329      * installed then this method verifies that its {@link
 330      * java.lang.SecurityManager#checkConnect checkConnect} method permits
 331      * connecting to the address and port number of the given remote endpoint.
 332      *
 333      * <p> This method may be invoked at any time.  If a read or write
 334      * operation upon this channel is invoked while an invocation of this
 335      * method is in progress then that operation will first block until this
 336      * invocation is complete.  If a connection attempt is initiated but fails,
 337      * that is, if an invocation of this method throws a checked exception,
 338      * then the channel will be closed.  </p>
 339      *
 340      * @param  remote
 341      *         The remote address to which this channel is to be connected
 342      *
 343      * @return  <tt>true</tt> if a connection was established,
 344      *          <tt>false</tt> if this channel is in non-blocking mode
 345      *          and the connection operation is in progress
 346      *
 347      * @throws  AlreadyConnectedException
 348      *          If this channel is already connected
 349      *
 350      * @throws  ConnectionPendingException
 351      *          If a non-blocking connection operation is already in progress
 352      *          on this channel
 353      *
 354      * @throws  ClosedChannelException
 355      *          If this channel is closed
 356      *
 357      * @throws  AsynchronousCloseException
 358      *          If another thread closes this channel
 359      *          while the connect operation is in progress
 360      *
 361      * @throws  ClosedByInterruptException
 362      *          If another thread interrupts the current thread
 363      *          while the connect operation is in progress, thereby
 364      *          closing the channel and setting the current thread's
 365      *          interrupt status
 366      *
 367      * @throws  UnresolvedAddressException
 368      *          If the given remote address is not fully resolved
 369      *
 370      * @throws  UnsupportedAddressTypeException
 371      *          If the type of the given remote address is not supported
 372      *
 373      * @throws  SecurityException
 374      *          If a security manager has been installed
 375      *          and it does not permit access to the given remote endpoint
 376      *
 377      * @throws  IOException
 378      *          If some other I/O error occurs
 379      */
 380     public abstract boolean connect(SocketAddress remote) throws IOException;
 381 
 382     /**
 383      * Finishes the process of connecting a socket channel.
 384      *
 385      * <p> A non-blocking connection operation is initiated by placing a socket
 386      * channel in non-blocking mode and then invoking its {@link #connect
 387      * connect} method.  Once the connection is established, or the attempt has
 388      * failed, the socket channel will become connectable and this method may
 389      * be invoked to complete the connection sequence.  If the connection
 390      * operation failed then invoking this method will cause an appropriate
 391      * {@link java.io.IOException} to be thrown.
 392      *
 393      * <p> If this channel is already connected then this method will not block
 394      * and will immediately return <tt>true</tt>.  If this channel is in
 395      * non-blocking mode then this method will return <tt>false</tt> if the
 396      * connection process is not yet complete.  If this channel is in blocking
 397      * mode then this method will block until the connection either completes
 398      * or fails, and will always either return <tt>true</tt> or throw a checked
 399      * exception describing the failure.
 400      *
 401      * <p> This method may be invoked at any time.  If a read or write
 402      * operation upon this channel is invoked while an invocation of this
 403      * method is in progress then that operation will first block until this
 404      * invocation is complete.  If a connection attempt fails, that is, if an
 405      * invocation of this method throws a checked exception, then the channel
 406      * will be closed.  </p>
 407      *
 408      * @return  <tt>true</tt> if, and only if, this channel's socket is now
 409      *          connected
 410      *
 411      * @throws  NoConnectionPendingException
 412      *          If this channel is not connected and a connection operation
 413      *          has not been initiated
 414      *
 415      * @throws  ClosedChannelException
 416      *          If this channel is closed
 417      *
 418      * @throws  AsynchronousCloseException
 419      *          If another thread closes this channel
 420      *          while the connect operation is in progress
 421      *
 422      * @throws  ClosedByInterruptException
 423      *          If another thread interrupts the current thread
 424      *          while the connect operation is in progress, thereby
 425      *          closing the channel and setting the current thread's
 426      *          interrupt status
 427      *
 428      * @throws  IOException
 429      *          If some other I/O error occurs
 430      */
 431     public abstract boolean finishConnect() throws IOException;
 432 
 433     /**
 434      * Returns the remote address to which this channel's socket is connected.
 435      *
 436      * <p> Where the channel is bound and connected to an Internet Protocol
 437      * socket address then the return value from this method is of type {@link
 438      * java.net.InetSocketAddress}.
 439      *
 440      * @return  The remote address; {@code null} if the channel's socket is not
 441      *          connected
 442      *
 443      * @throws  ClosedChannelException
 444      *          If the channel is closed
 445      * @throws  IOException
 446      *          If an I/O error occurs
 447      *
 448      * @since 1.7
 449      */
 450     public abstract SocketAddress getRemoteAddress() throws IOException;
 451 
 452     // -- ByteChannel operations --
 453 
 454     /**
 455      * @throws  NotYetConnectedException
 456      *          If this channel is not yet connected
 457      */
 458     public abstract int read(ByteBuffer dst) throws IOException;
 459 
 460     /**
 461      * @throws  NotYetConnectedException
 462      *          If this channel is not yet connected
 463      */
 464     public abstract long read(ByteBuffer[] dsts, int offset, int length)
 465         throws IOException;
 466 
 467     /**
 468      * @throws  NotYetConnectedException
 469      *          If this channel is not yet connected
 470      */
 471     public final long read(ByteBuffer[] dsts) throws IOException {
 472         return read(dsts, 0, dsts.length);
 473     }
 474 
 475     /**
 476      * @throws  NotYetConnectedException
 477      *          If this channel is not yet connected
 478      */
 479     public abstract int write(ByteBuffer src) throws IOException;
 480 
 481     /**
 482      * @throws  NotYetConnectedException
 483      *          If this channel is not yet connected
 484      */
 485     public abstract long write(ByteBuffer[] srcs, int offset, int length)
 486         throws IOException;
 487 
 488     /**
 489      * @throws  NotYetConnectedException
 490      *          If this channel is not yet connected
 491      */
 492     public final long write(ByteBuffer[] srcs) throws IOException {
 493         return write(srcs, 0, srcs.length);
 494     }
 495 
 496 }