Path: blob/master/src/java.base/share/classes/java/nio/channels/ServerSocketChannel.java
41159 views
/*1* Copyright (c) 2000, 2020, 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.io.IOException;28import java.net.InetSocketAddress;29import java.net.NetPermission;30import java.net.ProtocolFamily;31import java.net.ServerSocket;32import java.net.SocketOption;33import java.net.SocketAddress;34import java.net.UnixDomainSocketAddress;35import java.nio.channels.spi.AbstractSelectableChannel;36import java.nio.channels.spi.SelectorProvider;37import static java.util.Objects.requireNonNull;3839/**40* A selectable channel for stream-oriented listening sockets.41*42* <p> A server-socket channel is created by invoking one of the {@code open}43* methods of this class. The no-arg {@link #open() open} method opens a server-socket44* channel for an <i>Internet protocol</i> socket. The {@link #open(ProtocolFamily)}45* method is used to open a server-socket channel for a socket of a specified46* protocol family. It is not possible to create a channel for an arbitrary,47* pre-existing socket. A newly-created server-socket channel is open but not yet48* bound. An attempt to invoke the {@link #accept() accept} method of an49* unbound server-socket channel will cause a {@link NotYetBoundException}50* to be thrown. A server-socket channel can be bound by invoking one of the51* {@link #bind(java.net.SocketAddress, int) bind} methods defined by this class.52*53* <p> Socket options are configured using the {@link #setOption(SocketOption,Object)54* setOption} method. Server-socket channels for <i>Internet protocol</i> sockets55* support the following options:56* <blockquote>57* <table class="striped">58* <caption style="display:none">Socket options</caption>59* <thead>60* <tr>61* <th scope="col">Option Name</th>62* <th scope="col">Description</th>63* </tr>64* </thead>65* <tbody>66* <tr>67* <th scope="row"> {@link java.net.StandardSocketOptions#SO_RCVBUF SO_RCVBUF} </th>68* <td> The size of the socket receive buffer </td>69* </tr>70* <tr>71* <th scope="row"> {@link java.net.StandardSocketOptions#SO_REUSEADDR SO_REUSEADDR} </th>72* <td> Re-use address </td>73* </tr>74* </tbody>75* </table>76* </blockquote>77*78* <p> Server-socket channels for <i>Unix domain</i> sockets support:79* <blockquote>80* <table class="striped">81* <caption style="display:none">Socket options</caption>82* <thead>83* <tr>84* <th scope="col">Option Name</th>85* <th scope="col">Description</th>86* </tr>87* </thead>88* <tbody>89* <tr>90* <th scope="row"> {@link java.net.StandardSocketOptions#SO_RCVBUF SO_RCVBUF} </th>91* <td> The size of the socket receive buffer </td>92* </tr>93* </tbody>94* </table>95* </blockquote>96*97* <p> Additional (implementation specific) options may also be supported.98*99* <p> Server-socket channels are safe for use by multiple concurrent threads.100* </p>101*102* @author Mark Reinhold103* @author JSR-51 Expert Group104* @since 1.4105*/106107public abstract class ServerSocketChannel108extends AbstractSelectableChannel109implements NetworkChannel110{111112/**113* Initializes a new instance of this class.114*115* @param provider116* The provider that created this channel117*/118protected ServerSocketChannel(SelectorProvider provider) {119super(provider);120}121122/**123* Opens a server-socket channel for an <i>Internet protocol</i> socket.124*125* <p> The new channel is created by invoking the {@link126* java.nio.channels.spi.SelectorProvider#openServerSocketChannel127* openServerSocketChannel} method of the system-wide default {@link128* java.nio.channels.spi.SelectorProvider} object.129*130* <p> The new channel's socket is initially unbound; it must be bound to a131* specific address via one of its socket's {@link132* java.net.ServerSocket#bind(SocketAddress) bind} methods before133* connections can be accepted. </p>134*135* @return A new socket channel136*137* @throws IOException138* If an I/O error occurs139*140* @see <a href="../../net/doc-files/net-properties.html#Ipv4IPv6">141* java.net.preferIPv4Stack</a> system property142*/143public static ServerSocketChannel open() throws IOException {144return SelectorProvider.provider().openServerSocketChannel();145}146147/**148* Opens a server-socket channel. The {@code family} parameter specifies the149* {@link ProtocolFamily protocol family} of the channel's socket.150*151* <p> The new channel is created by invoking the {@link152* java.nio.channels.spi.SelectorProvider#openServerSocketChannel(ProtocolFamily)153* openServerSocketChannel(ProtocolFamily)} method of the system-wide default {@link154* java.nio.channels.spi.SelectorProvider} object. </p>155*156* @param family157* The protocol family158*159* @return A new socket channel160*161* @throws UnsupportedOperationException162* If the specified protocol family is not supported. For example,163* suppose the parameter is specified as {@link164* java.net.StandardProtocolFamily#INET6 StandardProtocolFamily.INET6}165* but IPv6 is not enabled on the platform.166* @throws IOException167* If an I/O error occurs168*169* @see <a href="../../net/doc-files/net-properties.html#Ipv4IPv6">170* java.net.preferIPv4Stack</a> system property171*172* @since 15173*/174public static ServerSocketChannel open(ProtocolFamily family) throws IOException {175return SelectorProvider.provider().openServerSocketChannel(requireNonNull(family));176}177178/**179* Returns an operation set identifying this channel's supported180* operations.181*182* <p> Server-socket channels only support the accepting of new183* connections, so this method returns {@link SelectionKey#OP_ACCEPT}.184* </p>185*186* @return The valid-operation set187*/188public final int validOps() {189return SelectionKey.OP_ACCEPT;190}191192193// -- ServerSocket-specific operations --194195/**196* Binds the channel's socket to a local address and configures the socket197* to listen for connections.198*199* <p> An invocation of this method is equivalent to the following:200* <blockquote><pre>201* bind(local, 0);202* </pre></blockquote>203*204* @param local205* The local address to bind the socket, or {@code null} to bind206* to an automatically assigned socket address207*208* @return This channel209*210* @throws AlreadyBoundException {@inheritDoc}211* @throws UnsupportedAddressTypeException {@inheritDoc}212* @throws ClosedChannelException {@inheritDoc}213* @throws IOException {@inheritDoc}214* @throws SecurityException215* If a security manager has been installed and it denies the216* operation217*218* @since 1.7219*/220public final ServerSocketChannel bind(SocketAddress local)221throws IOException222{223return bind(local, 0);224}225226/**227* Binds the channel's socket to a local address and configures the socket to228* listen for connections.229*230* <p> This method is used to establish an association between the socket and231* a local address. For <i>Internet protocol</i> sockets, once an association232* is established then the socket remains bound until the channel is closed.233*234* <p> The {@code backlog} parameter is the maximum number of pending235* connections on the socket. Its exact semantics are implementation specific.236* In particular, an implementation may impose a maximum length or may choose237* to ignore the parameter altogether. If the {@code backlog} parameter has238* the value {@code 0}, or a negative value, then an implementation specific239* default is used.240*241* @apiNote242* Binding a server socket channel for a <i>Unix Domain</i> socket, creates a243* file corresponding to the file path in the {@link UnixDomainSocketAddress}.244* This file persists after the channel is closed, and must be removed before245* another socket can bind to the same name. Binding to a {@code null} address246* causes the socket to be <i>automatically</i> bound to some unique file247* in a system temporary location. The associated socket file also persists248* after the channel is closed. Its name can be obtained from the channel's249* local socket address.250*251* @implNote252* Each platform enforces an implementation specific, maximum length for the253* name of a <i>Unix Domain</i> socket. This limitation is enforced when a254* channel is bound. The maximum length is typically close to and generally255* not less than 100 bytes. This limitation also applies to <i>automatically</i>256* bound server socket channels. See the <i>Unix domain</i>257* <a href="../../net/doc-files/net-properties.html#Unixdomain">networking258* properties</a> that can be used to select the temporary directory where259* these sockets are created.260*261* @param local262* The address to bind the socket, or {@code null} to bind to263* an automatically assigned socket address264* @param backlog265* The maximum number of pending connections266*267* @return This channel268*269* @throws AlreadyBoundException270* If the socket is already bound271* @throws UnsupportedAddressTypeException272* If the type of the given address is not supported273* @throws ClosedChannelException274* If this channel is closed275* @throws IOException276* If some other I/O error occurs277* @throws SecurityException278* If a security manager has been installed and its {@link279* SecurityManager#checkListen checkListen} method denies280* the operation for an <i>Internet protocol</i> socket address,281* or for a <i>Unix domain</i> socket address if it denies282* {@link NetPermission}{@code("accessUnixDomainSocket")}.283*284* @since 1.7285*/286public abstract ServerSocketChannel bind(SocketAddress local, int backlog)287throws IOException;288289/**290* @throws UnsupportedOperationException {@inheritDoc}291* @throws IllegalArgumentException {@inheritDoc}292* @throws ClosedChannelException {@inheritDoc}293* @throws IOException {@inheritDoc}294*295* @since 1.7296*/297public abstract <T> ServerSocketChannel setOption(SocketOption<T> name, T value)298throws IOException;299300/**301* Retrieves a server socket associated with this channel.302*303* <p> The returned object will not declare any public methods that are not304* declared in the {@link java.net.ServerSocket} class. </p>305*306* @return A server socket associated with this channel307*308* @throws UnsupportedOperationException309* If the channel's socket is not an <i>Internet protocol</i> socket310*/311public abstract ServerSocket socket();312313/**314* Accepts a connection made to this channel's socket.315*316* <p> If this channel is in non-blocking mode then this method will317* immediately return {@code null} if there are no pending connections.318* Otherwise it will block indefinitely until a new connection is available319* or an I/O error occurs.320*321* <p> The socket channel returned by this method, if any, will be in322* blocking mode regardless of the blocking mode of this channel.323*324* <p> If bound to an <i>Internet protocol</i> socket address, this method325* performs exactly the same security checks as the {@link326* java.net.ServerSocket#accept accept} method of the {@link java.net.ServerSocket}327* class. That is, if a security manager has been installed then for each328* new connection this method verifies that the address and port number329* of the connection's remote endpoint are permitted by the security330* manager's {@link java.lang.SecurityManager#checkAccept checkAccept}331* method. If bound to a <i>Unix Domain</i> socket address, this method checks332* {@link NetPermission}{@code ("accessUnixDomainSocket")}.333*334* @return The socket channel for the new connection,335* or {@code null} if this channel is in non-blocking mode336* and no connection is available to be accepted337*338* @throws ClosedChannelException339* If this channel is closed340*341* @throws AsynchronousCloseException342* If another thread closes this channel343* while the accept operation is in progress344*345* @throws ClosedByInterruptException346* If another thread interrupts the current thread347* while the accept operation is in progress, thereby348* closing the channel and setting the current thread's349* interrupt status350*351* @throws NotYetBoundException352* If this channel's socket has not yet been bound353*354* @throws SecurityException355* If a security manager has been installed and this356* channel is bound to an {@link InetSocketAddress}357* and the security manager denies access to the remote endpoint358* of the new connection, or if this channel is bound to a359* {@link UnixDomainSocketAddress} and the security manager360* denies {@link NetPermission}{@code ("accessUnixDomainSocket")}361*362* @throws IOException363* If some other I/O error occurs364*/365public abstract SocketChannel accept() throws IOException;366367/**368* {@inheritDoc}369*370* If there is a security manager set, its {@code checkConnect} method is371* called with the local address and {@code -1} as its arguments to see372* if the operation is allowed. If the operation is not allowed,373* a {@code SocketAddress} representing the374* {@link java.net.InetAddress#getLoopbackAddress loopback} address and the375* local port of the channel's socket is returned.376*377* <p> Where the channel is bound to a <i>Unix Domain</i> socket address, the socket378* address is a {@link UnixDomainSocketAddress}. If there is a security manager379* set, its {@link SecurityManager#checkPermission(java.security.Permission)380* checkPermission} method is called with {@link NetPermission}{@code381* ("accessUnixDomainSocket")}. If the operation is not allowed an unnamed382* {@link UnixDomainSocketAddress} is returned.383*384* @return The {@code SocketAddress} that the socket is bound to, or the385* {@code SocketAddress} representing the loopback address or empty386* path if denied by the security manager, or {@code null} if the387* channel's socket is not bound388*389* @throws ClosedChannelException {@inheritDoc}390* @throws IOException {@inheritDoc}391*/392@Override393public abstract SocketAddress getLocalAddress() throws IOException;394}395396397