1 /*
   2  * Copyright (c) 2007, 2013, 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.nio.channels.spi.*;
  29 import java.net.SocketOption;
  30 import java.net.SocketAddress;
  31 import java.util.concurrent.Future;
  32 import java.io.IOException;
  33 
  34 /**
  35  * An asynchronous channel for stream-oriented listening sockets.
  36  *
  37  * <p> An asynchronous server-socket channel is created by invoking the
  38  * {@link #open open} method of this class.
  39  * A newly-created asynchronous server-socket channel is open but not yet bound.
  40  * It can be bound to a local address and configured to listen for connections
  41  * by invoking the {@link #bind(SocketAddress,int) bind} method. Once bound,
  42  * the {@link #accept(Object,CompletionHandler) accept} method
  43  * is used to initiate the accepting of connections to the channel's socket.
  44  * An attempt to invoke the {@code accept} method on an unbound channel will
  45  * cause a {@link NotYetBoundException} to be thrown.
  46  *
  47  * <p> Channels of this type are safe for use by multiple concurrent threads
  48  * though at most one accept operation can be outstanding at any time.
  49  * If a thread initiates an accept operation before a previous accept operation
  50  * has completed then an {@link AcceptPendingException} will be thrown.
  51  *
  52  * <p> Socket options are configured using the {@link #setOption(SocketOption,Object)
  53  * setOption} method. Channels of this type support the following options:
  54  * <blockquote>
  55  * <table border summary="Socket options">
  56  *   <tr>
  57  *     <th>Option Name</th>
  58  *     <th>Description</th>
  59  *   </tr>
  60  *   <tr>
  61  *     <td> {@link java.net.StandardSocketOptions#SO_RCVBUF SO_RCVBUF} </td>
  62  *     <td> The size of the socket receive buffer </td>
  63  *   </tr>
  64  *   <tr>
  65  *     <td> {@link java.net.StandardSocketOptions#SO_REUSEADDR SO_REUSEADDR} </td>
  66  *     <td> Re-use address </td>
  67  *   </tr>
  68  * </table>
  69  * </blockquote>
  70  * Additional (implementation specific) options may also be supported.
  71  *
  72  * <p> <b>Usage Example:</b>
  73  * <pre>
  74  *  final AsynchronousServerSocketChannel listener =
  75  *      AsynchronousServerSocketChannel.open().bind(new InetSocketAddress(5000));
  76  *
  77  *  listener.accept(null, new CompletionHandler&lt;AsynchronousSocketChannel,Void&gt;() {
  78  *      public void completed(AsynchronousSocketChannel ch, Void att) {
  79  *          // accept the next connection
  80  *          listener.accept(null, this);
  81  *
  82  *          // handle this connection
  83  *          handle(ch);
  84  *      }
  85  *      public void failed(Throwable exc, Void att) {
  86  *          ...
  87  *      }
  88  *  });
  89  * </pre>
  90  *
  91  * @since 1.7
  92  */
  93 
  94 public abstract class AsynchronousServerSocketChannel
  95     implements AsynchronousChannel, NetworkChannel
  96 {
  97     private final AsynchronousChannelProvider provider;
  98 
  99     /**
 100      * Initializes a new instance of this class.
 101      *
 102      * @param  provider
 103      *         The provider that created this channel
 104      */
 105     protected AsynchronousServerSocketChannel(AsynchronousChannelProvider provider) {
 106         this.provider = provider;
 107     }
 108 
 109     /**
 110      * Returns the provider that created this channel.
 111      *
 112      * @return  The provider that created this channel
 113      */
 114     public final AsynchronousChannelProvider provider() {
 115         return provider;
 116     }
 117 
 118     /**
 119      * Opens an asynchronous server-socket channel.
 120      *
 121      * <p> The new channel is created by invoking the {@link
 122      * java.nio.channels.spi.AsynchronousChannelProvider#openAsynchronousServerSocketChannel
 123      * openAsynchronousServerSocketChannel} method on the {@link
 124      * java.nio.channels.spi.AsynchronousChannelProvider} object that created
 125      * the given group. If the group parameter is {@code null} then the
 126      * resulting channel is created by the system-wide default provider, and
 127      * bound to the <em>default group</em>.
 128      *
 129      * @param   group
 130      *          The group to which the newly constructed channel should be bound,
 131      *          or {@code null} for the default group
 132      *
 133      * @return  A new asynchronous server socket channel
 134      *
 135      * @throws  ShutdownChannelGroupException
 136      *          If the channel group is shutdown
 137      * @throws  IOException
 138      *          If an I/O error occurs
 139      */
 140     public static AsynchronousServerSocketChannel open(AsynchronousChannelGroup group)
 141         throws IOException
 142     {
 143         AsynchronousChannelProvider provider = (group == null) ?
 144             AsynchronousChannelProvider.provider() : group.provider();
 145         return provider.openAsynchronousServerSocketChannel(group);
 146     }
 147 
 148     /**
 149      * Opens an asynchronous server-socket channel.
 150      *
 151      * <p> This method returns an asynchronous server socket channel that is
 152      * bound to the <em>default group</em>. This method is equivalent to evaluating
 153      * the expression:
 154      * <blockquote><pre>
 155      * open((AsynchronousChannelGroup)null);
 156      * </pre></blockquote>
 157      *
 158      * @return  A new asynchronous server socket channel
 159      *
 160      * @throws  IOException
 161      *          If an I/O error occurs
 162      */
 163     public static AsynchronousServerSocketChannel open()
 164         throws IOException
 165     {
 166         return open(null);
 167     }
 168 
 169     /**
 170      * Binds the channel's socket to a local address and configures the socket to
 171      * listen for connections.
 172      *
 173      * <p> An invocation of this method is equivalent to the following:
 174      * <blockquote><pre>
 175      * bind(local, 0);
 176      * </pre></blockquote>
 177      *
 178      * @param   local
 179      *          The local address to bind the socket, or {@code null} to bind
 180      *          to an automatically assigned socket address
 181      *
 182      * @return  This channel
 183      *
 184      * @throws  AlreadyBoundException               {@inheritDoc}
 185      * @throws  UnsupportedAddressTypeException     {@inheritDoc}
 186      * @throws  SecurityException                   {@inheritDoc}
 187      * @throws  ClosedChannelException              {@inheritDoc}
 188      * @throws  IOException                         {@inheritDoc}
 189      */
 190     public final AsynchronousServerSocketChannel bind(SocketAddress local)
 191         throws IOException
 192     {
 193         return bind(local, 0);
 194     }
 195 
 196     /**
 197      * Binds the channel's socket to a local address and configures the socket to
 198      * listen for connections.
 199      *
 200      * <p> This method is used to establish an association between the socket and
 201      * a local address. Once an association is established then the socket remains
 202      * bound until the associated channel is closed.
 203      *
 204      * <p> The {@code backlog} parameter is the maximum number of pending
 205      * connections on the socket. Its exact semantics are implementation specific.
 206      * In particular, an implementation may impose a maximum length or may choose
 207      * to ignore the parameter altogther. If the {@code backlog} parameter has
 208      * the value {@code 0}, or a negative value, then an implementation specific
 209      * default is used.
 210      *
 211      * @param   local
 212      *          The local address to bind the socket, or {@code null} to bind
 213      *          to an automatically assigned socket address
 214      * @param   backlog
 215      *          The maximum number of pending connections
 216      *
 217      * @return  This channel
 218      *
 219      * @throws  AlreadyBoundException
 220      *          If the socket is already bound
 221      * @throws  UnsupportedAddressTypeException
 222      *          If the type of the given address is not supported
 223      * @throws  SecurityException
 224      *          If a security manager has been installed and its {@link
 225      *          SecurityManager#checkListen checkListen} method denies the operation
 226      * @throws  ClosedChannelException
 227      *          If the channel is closed
 228      * @throws  IOException
 229      *          If some other I/O error occurs
 230      */
 231     public abstract AsynchronousServerSocketChannel bind(SocketAddress local, int backlog)
 232         throws IOException;
 233 
 234     /**
 235      * @throws  IllegalArgumentException                {@inheritDoc}
 236      * @throws  ClosedChannelException                  {@inheritDoc}
 237      * @throws  IOException                             {@inheritDoc}
 238      */
 239     public abstract <T> AsynchronousServerSocketChannel setOption(SocketOption<T> name, T value)
 240         throws IOException;
 241 
 242     /**
 243      * Accepts a connection.
 244      *
 245      * <p> This method initiates an asynchronous operation to accept a
 246      * connection made to this channel's socket. The {@code handler} parameter is
 247      * a completion handler that is invoked when a connection is accepted (or
 248      * the operation fails). The result passed to the completion handler is
 249      * the {@link AsynchronousSocketChannel} to the new connection.
 250      *
 251      * <p> When a new connection is accepted then the resulting {@code
 252      * AsynchronousSocketChannel} will be bound to the same {@link
 253      * AsynchronousChannelGroup} as this channel. If the group is {@link
 254      * AsynchronousChannelGroup#isShutdown shutdown} and a connection is accepted,
 255      * then the connection is closed, and the operation completes with an {@code
 256      * IOException} and cause {@link ShutdownChannelGroupException}.
 257      *
 258      * <p> To allow for concurrent handling of new connections, the completion
 259      * handler is not invoked directly by the initiating thread when a new
 260      * connection is accepted immediately (see <a
 261      * href="AsynchronousChannelGroup.html#threading">Threading</a>).
 262      *
 263      * <p> If a security manager has been installed then it verifies that the
 264      * address and port number of the connection's remote endpoint are permitted
 265      * by the security manager's {@link SecurityManager#checkAccept checkAccept}
 266      * method. The permission check is performed with privileges that are restricted
 267      * by the calling context of this method. If the permission check fails then
 268      * the connection is closed and the operation completes with a {@link
 269      * SecurityException}.
 270      *
 271      * @param   <A>
 272      *          The type of the attachment
 273      * @param   attachment
 274      *          The object to attach to the I/O operation; can be {@code null}
 275      * @param   handler
 276      *          The handler for consuming the result
 277      *
 278      * @throws  AcceptPendingException
 279      *          If an accept operation is already in progress on this channel
 280      * @throws  NotYetBoundException
 281      *          If this channel's socket has not yet been bound
 282      * @throws  ShutdownChannelGroupException
 283      *          If the channel group has terminated
 284      */
 285     public abstract <A> void accept(A attachment,
 286                                     CompletionHandler<AsynchronousSocketChannel,? super A> handler);
 287 
 288     /**
 289      * Accepts a connection.
 290      *
 291      * <p> This method initiates an asynchronous operation to accept a
 292      * connection made to this channel's socket. The method behaves in exactly
 293      * the same manner as the {@link #accept(Object, CompletionHandler)} method
 294      * except that instead of specifying a completion handler, this method
 295      * returns a {@code Future} representing the pending result. The {@code
 296      * Future}'s {@link Future#get() get} method returns the {@link
 297      * AsynchronousSocketChannel} to the new connection on successful completion.
 298      *
 299      * @return  a {@code Future} object representing the pending result
 300      *
 301      * @throws  AcceptPendingException
 302      *          If an accept operation is already in progress on this channel
 303      * @throws  NotYetBoundException
 304      *          If this channel's socket has not yet been bound
 305      */
 306     public abstract Future<AsynchronousSocketChannel> accept();
 307 
 308     /**
 309      * {@inheritDoc}
 310      * <p>
 311      * If there is a security manager set, its {@code checkConnect} method is
 312      * called with the local address and {@code -1} as its arguments to see
 313      * if the operation is allowed. If the operation is not allowed,
 314      * a {@code SocketAddress} representing the
 315      * {@link java.net.InetAddress#getLoopbackAddress loopback} address and the
 316      * local port of the channel's socket is returned.
 317      *
 318      * @return  The {@code SocketAddress} that the socket is bound to, or the
 319      *          {@code SocketAddress} representing the loopback address if
 320      *          denied by the security manager, or {@code null} if the
 321      *          channel's socket is not bound
 322      *
 323      * @throws  ClosedChannelException     {@inheritDoc}
 324      * @throws  IOException                {@inheritDoc}
 325      */
 326     @Override
 327     public abstract SocketAddress getLocalAddress() throws IOException;
 328 }