1 /*
  2  * Copyright (c) 2000, 2020, 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.ProtocolFamily;
 30 import java.net.ServerSocket;
 31 import java.net.SocketOption;
 32 import java.net.SocketAddress;
 33 import java.nio.channels.spi.AbstractSelectableChannel;
 34 import java.nio.channels.spi.SelectorProvider;
 35 import static java.util.Objects.requireNonNull;
 36 
 37 /**
 38  * A selectable channel for stream-oriented listening sockets.
 39  *
 40  * <p> A server-socket channel is created by invoking the {@link #open() open}
 41  * method of this class.  It is not possible to create a channel for an arbitrary,
 42  * pre-existing {@link ServerSocket}. A newly-created server-socket channel is
 43  * open but not yet bound.  An attempt to invoke the {@link #accept() accept}
 44  * method of an unbound server-socket channel will cause a {@link NotYetBoundException}
 45  * to be thrown. A server-socket channel can be bound by invoking one of the
 46  * {@link #bind(java.net.SocketAddress,int) bind} methods defined by this class.
 47  *
 48  * <p> Socket options are configured using the {@link #setOption(SocketOption,Object)
 49  * setOption} method. Server-socket channels support the following options:
 50  * <blockquote>
 51  * <table class="striped">
 52  * <caption style="display:none">Socket options</caption>
 53  * <thead>
 54  *   <tr>
 55  *     <th scope="col">Option Name</th>
 56  *     <th scope="col">Description</th>
 57  *   </tr>
 58  * </thead>
 59  * <tbody>
 60  *   <tr>
 61  *     <th scope="row"> {@link java.net.StandardSocketOptions#SO_RCVBUF SO_RCVBUF} </th>
 62  *     <td> The size of the socket receive buffer </td>
 63  *   </tr>
 64  *   <tr>
 65  *     <th scope="row"> {@link java.net.StandardSocketOptions#SO_REUSEADDR SO_REUSEADDR} </th>
 66  *     <td> Re-use address </td>
 67  *   </tr>
 68  * </tbody>
 69  * </table>
 70  * </blockquote>
 71  * Additional (implementation specific) options may also be supported.
 72  *
 73  * <p> Server-socket channels are safe for use by multiple concurrent threads.
 74  * </p>
 75  *
 76  * @author Mark Reinhold
 77  * @author JSR-51 Expert Group
 78  * @since 1.4
 79  */
 80 
 81 public abstract class ServerSocketChannel
 82     extends AbstractSelectableChannel
 83     implements NetworkChannel
 84 {
 85 
 86     /**
 87      * Initializes a new instance of this class.
 88      *
 89      * @param  provider
 90      *         The provider that created this channel
 91      */
 92     protected ServerSocketChannel(SelectorProvider provider) {
 93         super(provider);
 94     }
 95 
 96     /**
 97      * Opens a server-socket channel.
 98      *
 99      * <p> The new channel is created by invoking the {@link
100      * java.nio.channels.spi.SelectorProvider#openServerSocketChannel
101      * openServerSocketChannel} method of the system-wide default {@link
102      * java.nio.channels.spi.SelectorProvider} object.
103      *
104      * <p> The new channel's socket is initially unbound; it must be bound to a
105      * specific address via one of its socket's {@link
106      * java.net.ServerSocket#bind(SocketAddress) bind} methods before
107      * connections can be accepted.  </p>
108      *
109      * @return  A new socket channel
110      *
111      * @throws  IOException
112      *          If an I/O error occurs
113      */
114     public static ServerSocketChannel open() throws IOException {
115         return SelectorProvider.provider().openServerSocketChannel();
116     }
117 
118     /**
119      * Opens a server-socket channel.The {@code family} parameter specifies the
120      * {@link ProtocolFamily protocol family} of the channel's socket.
121      *
122      * <p> The new channel is created by invoking the {@link
123      * java.nio.channels.spi.SelectorProvider#openServerSocketChannel(ProtocolFamily)
124      * openServerSocketChannel(ProtocolFamily)} method of the system-wide default {@link
125      * java.nio.channels.spi.SelectorProvider} object. </p>
126      *
127      * @param   family
128      *          The protocol family
129      *
130      * @return  A new socket channel
131      *
132      * @throws  UnsupportedOperationException
133      *          If the specified protocol family is not supported. For example,
134      *          suppose the parameter is specified as {@link
135      *          java.net.StandardProtocolFamily#INET6 StandardProtocolFamily.INET6}
136      *          but IPv6 is not enabled on the platform.
137      * @throws  IOException
138      *          If an I/O error occurs
139      *
140      * @since 15
141      */
142     public static ServerSocketChannel open(ProtocolFamily family) throws IOException {
143         return SelectorProvider.provider().openServerSocketChannel(requireNonNull(family));
144     }
145 
146     /**
147      * Returns an operation set identifying this channel's supported
148      * operations.
149      *
150      * <p> Server-socket channels only support the accepting of new
151      * connections, so this method returns {@link SelectionKey#OP_ACCEPT}.
152      * </p>
153      *
154      * @return  The valid-operation set
155      */
156     public final int validOps() {
157         return SelectionKey.OP_ACCEPT;
158     }
159 
160 
161     // -- ServerSocket-specific operations --
162 
163     /**
164      * Binds the channel's socket to a local address and configures the socket
165      * to listen for connections.
166      *
167      * <p> An invocation of this method is equivalent to the following:
168      * <blockquote><pre>
169      * bind(local, 0);
170      * </pre></blockquote>
171      *
172      * @param   local
173      *          The local address to bind the socket, or {@code null} to bind
174      *          to an automatically assigned socket address
175      *
176      * @return  This channel
177      *
178      * @throws  AlreadyBoundException               {@inheritDoc}
179      * @throws  UnsupportedAddressTypeException     {@inheritDoc}
180      * @throws  ClosedChannelException              {@inheritDoc}
181      * @throws  IOException                         {@inheritDoc}
182      * @throws  SecurityException
183      *          If a security manager has been installed and its {@link
184      *          SecurityManager#checkListen checkListen} method denies the
185      *          operation
186      *
187      * @since 1.7
188      */
189     public final ServerSocketChannel bind(SocketAddress local)
190         throws IOException
191     {
192         return bind(local, 0);
193     }
194 
195     /**
196      * Binds the channel's socket to a local address and configures the socket to
197      * listen for connections.
198      *
199      * <p> This method is used to establish an association between the socket and
200      * a local address. Once an association is established then the socket remains
201      * bound until the channel is closed.
202      *
203      * <p> The {@code backlog} parameter is the maximum number of pending
204      * connections on the socket. Its exact semantics are implementation specific.
205      * In particular, an implementation may impose a maximum length or may choose
206      * to ignore the parameter altogther. If the {@code backlog} parameter has
207      * the value {@code 0}, or a negative value, then an implementation specific
208      * default is used.
209      *
210      * @param   local
211      *          The address to bind the socket, or {@code null} to bind to an
212      *          automatically assigned socket address
213      * @param   backlog
214      *          The maximum number of pending connections
215      *
216      * @return  This channel
217      *
218      * @throws  AlreadyBoundException
219      *          If the socket is already bound
220      * @throws  UnsupportedAddressTypeException
221      *          If the type of the given address is not supported
222      * @throws  ClosedChannelException
223      *          If this channel is closed
224      * @throws  IOException
225      *          If some other I/O error occurs
226      * @throws  SecurityException
227      *          If a security manager has been installed and its {@link
228      *          SecurityManager#checkListen checkListen} method denies the
229      *          operation
230      *
231      * @since 1.7
232      */
233     public abstract ServerSocketChannel bind(SocketAddress local, int backlog)
234         throws IOException;
235 
236     /**
237      * @throws  UnsupportedOperationException           {@inheritDoc}
238      * @throws  IllegalArgumentException                {@inheritDoc}
239      * @throws  ClosedChannelException                  {@inheritDoc}
240      * @throws  IOException                             {@inheritDoc}
241      *
242      * @since 1.7
243      */
244     public abstract <T> ServerSocketChannel setOption(SocketOption<T> name, T value)
245         throws IOException;
246 
247     /**
248      * Retrieves a server socket associated with this channel.
249      *
250      * <p> The returned object will not declare any public methods that are not
251      * declared in the {@link java.net.ServerSocket} class.  </p>
252      *
253      * @return  A server socket associated with this channel
254      */
255     public abstract ServerSocket socket();
256 
257     /**
258      * Accepts a connection made to this channel's socket.
259      *
260      * <p> If this channel is in non-blocking mode then this method will
261      * immediately return {@code null} if there are no pending connections.
262      * Otherwise it will block indefinitely until a new connection is available
263      * or an I/O error occurs.
264      *
265      * <p> The socket channel returned by this method, if any, will be in
266      * blocking mode regardless of the blocking mode of this channel.
267      *
268      * <p> This method performs exactly the same security checks as the {@link
269      * java.net.ServerSocket#accept accept} method of the {@link
270      * java.net.ServerSocket} class.  That is, if a security manager has been
271      * installed then for each new connection this method verifies that the
272      * address and port number of the connection's remote endpoint are
273      * permitted by the security manager's {@link
274      * java.lang.SecurityManager#checkAccept checkAccept} method.  </p>
275      *
276      * @return  The socket channel for the new connection,
277      *          or {@code null} if this channel is in non-blocking mode
278      *          and no connection is available to be accepted
279      *
280      * @throws  ClosedChannelException
281      *          If this channel is closed
282      *
283      * @throws  AsynchronousCloseException
284      *          If another thread closes this channel
285      *          while the accept operation is in progress
286      *
287      * @throws  ClosedByInterruptException
288      *          If another thread interrupts the current thread
289      *          while the accept operation is in progress, thereby
290      *          closing the channel and setting the current thread's
291      *          interrupt status
292      *
293      * @throws  NotYetBoundException
294      *          If this channel's socket has not yet been bound
295      *
296      * @throws  SecurityException
297      *          If a security manager has been installed
298      *          and it does not permit access to the remote endpoint
299      *          of the new connection
300      *
301      * @throws  IOException
302      *          If some other I/O error occurs
303      */
304     public abstract SocketChannel accept() throws IOException;
305 
306     /**
307      * {@inheritDoc}
308      * <p>
309      * If there is a security manager set, its {@code checkConnect} method is
310      * called with the local address and {@code -1} as its arguments to see
311      * if the operation is allowed. If the operation is not allowed,
312      * a {@code SocketAddress} representing the
313      * {@link java.net.InetAddress#getLoopbackAddress loopback} address and the
314      * local port of the channel's socket is returned.
315      *
316      * @return  The {@code SocketAddress} that the socket is bound to, or the
317      *          {@code SocketAddress} representing the loopback address if
318      *          denied by the security manager, or {@code null} if the
319      *          channel's socket is not bound
320      *
321      * @throws  ClosedChannelException     {@inheritDoc}
322      * @throws  IOException                {@inheritDoc}
323      */
324     @Override
325     public abstract SocketAddress getLocalAddress() throws IOException;
326 
327 }