Path: blob/master/src/java.base/share/classes/java/nio/channels/AsynchronousServerSocketChannel.java
41159 views
/*1* Copyright (c) 2007, 2017, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425package java.nio.channels;2627import java.nio.channels.spi.*;28import java.net.SocketOption;29import java.net.SocketAddress;30import java.util.concurrent.Future;31import java.io.IOException;3233/**34* An asynchronous channel for stream-oriented listening sockets.35*36* <p> An asynchronous server-socket channel is created by invoking the37* {@link #open open} method of this class.38* A newly-created asynchronous server-socket channel is open but not yet bound.39* It can be bound to a local address and configured to listen for connections40* by invoking the {@link #bind(SocketAddress,int) bind} method. Once bound,41* the {@link #accept(Object,CompletionHandler) accept} method42* is used to initiate the accepting of connections to the channel's socket.43* An attempt to invoke the {@code accept} method on an unbound channel will44* cause a {@link NotYetBoundException} to be thrown.45*46* <p> Channels of this type are safe for use by multiple concurrent threads47* though at most one accept operation can be outstanding at any time.48* If a thread initiates an accept operation before a previous accept operation49* has completed then an {@link AcceptPendingException} will be thrown.50*51* <p> Socket options are configured using the {@link #setOption(SocketOption,Object)52* setOption} method. Channels of this type support the following options:53* <blockquote>54* <table class="striped">55* <caption style="display:none">Socket options</caption>56* <thead>57* <tr>58* <th scope="col">Option Name</th>59* <th scope="col">Description</th>60* </tr>61* </thead>62* <tbody>63* <tr>64* <th scope="row"> {@link java.net.StandardSocketOptions#SO_RCVBUF SO_RCVBUF} </th>65* <td> The size of the socket receive buffer </td>66* </tr>67* <tr>68* <th scope="row"> {@link java.net.StandardSocketOptions#SO_REUSEADDR SO_REUSEADDR} </th>69* <td> Re-use address </td>70* </tr>71* </tbody>72* </table>73* </blockquote>74* Additional (implementation specific) options may also be supported.75*76* <p> <b>Usage Example:</b>77* <pre>78* final AsynchronousServerSocketChannel listener =79* AsynchronousServerSocketChannel.open().bind(new InetSocketAddress(5000));80*81* listener.accept(null, new CompletionHandler<AsynchronousSocketChannel,Void>() {82* public void completed(AsynchronousSocketChannel ch, Void att) {83* // accept the next connection84* listener.accept(null, this);85*86* // handle this connection87* handle(ch);88* }89* public void failed(Throwable exc, Void att) {90* ...91* }92* });93* </pre>94*95* @since 1.796*/9798public abstract class AsynchronousServerSocketChannel99implements AsynchronousChannel, NetworkChannel100{101private final AsynchronousChannelProvider provider;102103/**104* Initializes a new instance of this class.105*106* @param provider107* The provider that created this channel108*/109protected AsynchronousServerSocketChannel(AsynchronousChannelProvider provider) {110this.provider = provider;111}112113/**114* Returns the provider that created this channel.115*116* @return The provider that created this channel117*/118public final AsynchronousChannelProvider provider() {119return provider;120}121122/**123* Opens an asynchronous server-socket channel.124*125* <p> The new channel is created by invoking the {@link126* java.nio.channels.spi.AsynchronousChannelProvider#openAsynchronousServerSocketChannel127* openAsynchronousServerSocketChannel} method on the {@link128* java.nio.channels.spi.AsynchronousChannelProvider} object that created129* the given group. If the group parameter is {@code null} then the130* resulting channel is created by the system-wide default provider, and131* bound to the <em>default group</em>.132*133* @param group134* The group to which the newly constructed channel should be bound,135* or {@code null} for the default group136*137* @return A new asynchronous server socket channel138*139* @throws ShutdownChannelGroupException140* If the channel group is shutdown141* @throws IOException142* If an I/O error occurs143*/144public static AsynchronousServerSocketChannel open(AsynchronousChannelGroup group)145throws IOException146{147AsynchronousChannelProvider provider = (group == null) ?148AsynchronousChannelProvider.provider() : group.provider();149return provider.openAsynchronousServerSocketChannel(group);150}151152/**153* Opens an asynchronous server-socket channel.154*155* <p> This method returns an asynchronous server socket channel that is156* bound to the <em>default group</em>. This method is equivalent to evaluating157* the expression:158* <blockquote><pre>159* open((AsynchronousChannelGroup)null);160* </pre></blockquote>161*162* @return A new asynchronous server socket channel163*164* @throws IOException165* If an I/O error occurs166*/167public static AsynchronousServerSocketChannel open()168throws IOException169{170return open(null);171}172173/**174* Binds the channel's socket to a local address and configures the socket to175* listen for connections.176*177* <p> An invocation of this method is equivalent to the following:178* <blockquote><pre>179* bind(local, 0);180* </pre></blockquote>181*182* @param local183* The local address to bind the socket, or {@code null} to bind184* to an automatically assigned socket address185*186* @return This channel187*188* @throws AlreadyBoundException {@inheritDoc}189* @throws UnsupportedAddressTypeException {@inheritDoc}190* @throws SecurityException {@inheritDoc}191* @throws ClosedChannelException {@inheritDoc}192* @throws IOException {@inheritDoc}193*/194public final AsynchronousServerSocketChannel bind(SocketAddress local)195throws IOException196{197return bind(local, 0);198}199200/**201* Binds the channel's socket to a local address and configures the socket to202* listen for connections.203*204* <p> This method is used to establish an association between the socket and205* a local address. Once an association is established then the socket remains206* bound until the associated channel is closed.207*208* <p> The {@code backlog} parameter is the maximum number of pending209* connections on the socket. Its exact semantics are implementation specific.210* In particular, an implementation may impose a maximum length or may choose211* to ignore the parameter altogther. If the {@code backlog} parameter has212* the value {@code 0}, or a negative value, then an implementation specific213* default is used.214*215* @param local216* The local address to bind the socket, or {@code null} to bind217* to an automatically assigned socket address218* @param backlog219* The maximum number of pending connections220*221* @return This channel222*223* @throws AlreadyBoundException224* If the socket is already bound225* @throws UnsupportedAddressTypeException226* If the type of the given address is not supported227* @throws SecurityException228* If a security manager has been installed and its {@link229* SecurityManager#checkListen checkListen} method denies the operation230* @throws ClosedChannelException231* If the channel is closed232* @throws IOException233* If some other I/O error occurs234*/235public abstract AsynchronousServerSocketChannel bind(SocketAddress local, int backlog)236throws IOException;237238/**239* @throws IllegalArgumentException {@inheritDoc}240* @throws ClosedChannelException {@inheritDoc}241* @throws IOException {@inheritDoc}242*/243public abstract <T> AsynchronousServerSocketChannel setOption(SocketOption<T> name, T value)244throws IOException;245246/**247* Accepts a connection.248*249* <p> This method initiates an asynchronous operation to accept a250* connection made to this channel's socket. The {@code handler} parameter is251* a completion handler that is invoked when a connection is accepted (or252* the operation fails). The result passed to the completion handler is253* the {@link AsynchronousSocketChannel} to the new connection.254*255* <p> When a new connection is accepted then the resulting {@code256* AsynchronousSocketChannel} will be bound to the same {@link257* AsynchronousChannelGroup} as this channel. If the group is {@link258* AsynchronousChannelGroup#isShutdown shutdown} and a connection is accepted,259* then the connection is closed, and the operation completes with an {@code260* IOException} and cause {@link ShutdownChannelGroupException}.261*262* <p> To allow for concurrent handling of new connections, the completion263* handler is not invoked directly by the initiating thread when a new264* connection is accepted immediately (see <a265* href="AsynchronousChannelGroup.html#threading">Threading</a>).266*267* <p> If a security manager has been installed then it verifies that the268* address and port number of the connection's remote endpoint are permitted269* by the security manager's {@link SecurityManager#checkAccept checkAccept}270* method. The permission check is performed with privileges that are restricted271* by the calling context of this method. If the permission check fails then272* the connection is closed and the operation completes with a {@link273* SecurityException}.274*275* @param <A>276* The type of the attachment277* @param attachment278* The object to attach to the I/O operation; can be {@code null}279* @param handler280* The handler for consuming the result281*282* @throws AcceptPendingException283* If an accept operation is already in progress on this channel284* @throws NotYetBoundException285* If this channel's socket has not yet been bound286* @throws ShutdownChannelGroupException287* If the channel group has terminated288*/289public abstract <A> void accept(A attachment,290CompletionHandler<AsynchronousSocketChannel,? super A> handler);291292/**293* Accepts a connection.294*295* <p> This method initiates an asynchronous operation to accept a296* connection made to this channel's socket. The method behaves in exactly297* the same manner as the {@link #accept(Object, CompletionHandler)} method298* except that instead of specifying a completion handler, this method299* returns a {@code Future} representing the pending result. The {@code300* Future}'s {@link Future#get() get} method returns the {@link301* AsynchronousSocketChannel} to the new connection on successful completion.302*303* @return a {@code Future} object representing the pending result304*305* @throws AcceptPendingException306* If an accept operation is already in progress on this channel307* @throws NotYetBoundException308* If this channel's socket has not yet been bound309*/310public abstract Future<AsynchronousSocketChannel> accept();311312/**313* {@inheritDoc}314* <p>315* If there is a security manager set, its {@code checkConnect} method is316* called with the local address and {@code -1} as its arguments to see317* if the operation is allowed. If the operation is not allowed,318* a {@code SocketAddress} representing the319* {@link java.net.InetAddress#getLoopbackAddress loopback} address and the320* local port of the channel's socket is returned.321*322* @return The {@code SocketAddress} that the socket is bound to, or the323* {@code SocketAddress} representing the loopback address if324* denied by the security manager, or {@code null} if the325* channel's socket is not bound326*327* @throws ClosedChannelException {@inheritDoc}328* @throws IOException {@inheritDoc}329*/330@Override331public abstract SocketAddress getLocalAddress() throws IOException;332}333334335