Path: blob/master/src/java.base/share/classes/java/nio/channels/SocketChannel.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.StandardProtocolFamily;32import java.net.Socket;33import java.net.SocketOption;34import java.net.SocketAddress;35import java.net.UnixDomainSocketAddress;36import java.nio.ByteBuffer;37import java.nio.channels.spi.AbstractSelectableChannel;38import java.nio.channels.spi.SelectorProvider;39import static java.util.Objects.requireNonNull;4041/**42* A selectable channel for stream-oriented connecting sockets.43*44* <p> A socket channel is created by invoking one of the {@code open} methods of45* this class. The no-arg {@link #open() open} method opens a socket channel46* for an <i>Internet protocol</i> socket. The {@link #open(ProtocolFamily)}47* method is used to open a socket channel for a socket of a specified protocol48* family. It is not possible to create a channel for an arbitrary, pre-existing49* socket. A newly-created socket channel is open but not yet connected. An50* attempt to invoke an I/O operation upon an unconnected channel will cause a51* {@link NotYetConnectedException} to be thrown. A socket channel can be52* connected by invoking its {@link #connect connect} method; once connected,53* a socket channel remains connected until it is closed. Whether or not a54* socket channel is connected may be determined by invoking its {@link #isConnected()55* isConnected} method.56*57* <p> Socket channels support <i>non-blocking connection:</i> A socket58* channel may be created and the process of establishing the link to the59* remote socket may be initiated via the {@link #connect connect} method for60* later completion by the {@link #finishConnect finishConnect} method.61* Whether or not a connection operation is in progress may be determined by62* invoking the {@link #isConnectionPending isConnectionPending} method.63*64* <p> Socket channels support <i>asynchronous shutdown</i>, which is similar65* to the asynchronous close operation specified in the {@link Channel} class.66* If the input side of a socket is shut down by one thread while another67* thread is blocked in a read operation on the socket's channel, then the read68* operation in the blocked thread will complete without reading any bytes and69* will return {@code -1}. If the output side of a socket is shut down by one70* thread while another thread is blocked in a write operation on the socket's71* channel, then the blocked thread will receive an {@link72* AsynchronousCloseException}.73*74* <p> Socket options are configured using the {@link #setOption(SocketOption,Object)75* setOption} method. Socket channels for <i>Internet protocol</i> sockets support76* following options:77* <blockquote>78* <table class="striped">79* <caption style="display:none">Socket options</caption>80* <thead>81* <tr>82* <th scope="col">Option Name</th>83* <th scope="col">Description</th>84* </tr>85* </thead>86* <tbody>87* <tr>88* <th scope="row"> {@link java.net.StandardSocketOptions#SO_SNDBUF SO_SNDBUF} </th>89* <td> The size of the socket send buffer </td>90* </tr>91* <tr>92* <th scope="row"> {@link java.net.StandardSocketOptions#SO_RCVBUF SO_RCVBUF} </th>93* <td> The size of the socket receive buffer </td>94* </tr>95* <tr>96* <th scope="row"> {@link java.net.StandardSocketOptions#SO_KEEPALIVE SO_KEEPALIVE} </th>97* <td> Keep connection alive </td>98* </tr>99* <tr>100* <th scope="row"> {@link java.net.StandardSocketOptions#SO_REUSEADDR SO_REUSEADDR} </th>101* <td> Re-use address </td>102* </tr>103* <tr>104* <th scope="row"> {@link java.net.StandardSocketOptions#SO_LINGER SO_LINGER} </th>105* <td> Linger on close if data is present (when configured in blocking mode106* only) </td>107* </tr>108* <tr>109* <th scope="row"> {@link java.net.StandardSocketOptions#TCP_NODELAY TCP_NODELAY} </th>110* <td> Disable the Nagle algorithm </td>111* </tr>112* </tbody>113* </table>114* </blockquote>115*116* <p> Socket channels for <i>Unix domain</i> sockets support:117* <blockquote>118* <table class="striped">119* <caption style="display:none">Socket options</caption>120* <thead>121* <tr>122* <th scope="col">Option Name</th>123* <th scope="col">Description</th>124* </tr>125* </thead>126* <tbody>127* <tr>128* <th scope="row"> {@link java.net.StandardSocketOptions#SO_SNDBUF SO_SNDBUF} </th>129* <td> The size of the socket send buffer </td>130* </tr>131* <tr>132* <th scope="row"> {@link java.net.StandardSocketOptions#SO_RCVBUF SO_RCVBUF} </th>133* <td> The size of the socket receive buffer </td>134* </tr>135* <tr>136* <th scope="row"> {@link java.net.StandardSocketOptions#SO_LINGER SO_LINGER} </th>137* <td> Linger on close if data is present (when configured in blocking mode138* only) </td>139* </tr>140* </tbody>141* </table>142* </blockquote>143*144* <p> Additional (implementation specific) options may also be supported.145*146* <p> Socket channels are safe for use by multiple concurrent threads. They147* support concurrent reading and writing, though at most one thread may be148* reading and at most one thread may be writing at any given time. The {@link149* #connect connect} and {@link #finishConnect finishConnect} methods are150* mutually synchronized against each other, and an attempt to initiate a read151* or write operation while an invocation of one of these methods is in152* progress will block until that invocation is complete. </p>153*154* @author Mark Reinhold155* @author JSR-51 Expert Group156* @since 1.4157*/158159public abstract class SocketChannel160extends AbstractSelectableChannel161implements ByteChannel, ScatteringByteChannel, GatheringByteChannel, NetworkChannel162{163164/**165* Initializes a new instance of this class.166*167* @param provider168* The provider that created this channel169*/170protected SocketChannel(SelectorProvider provider) {171super(provider);172}173174/**175* Opens a socket channel for an <i>Internet protocol</i> socket.176*177* <p> The new channel is created by invoking the {@link178* java.nio.channels.spi.SelectorProvider#openSocketChannel179* openSocketChannel} method of the system-wide default {@link180* java.nio.channels.spi.SelectorProvider} object. </p>181*182* @return A new socket channel183*184* @throws IOException185* If an I/O error occurs186*187* @see <a href="../../net/doc-files/net-properties.html#Ipv4IPv6">188* java.net.preferIPv4Stack</a> system property189*/190public static SocketChannel open() throws IOException {191return SelectorProvider.provider().openSocketChannel();192}193194/**195* Opens a socket channel. The {@code family} parameter specifies the196* {@link ProtocolFamily protocol family} of the channel's socket.197*198* <p> The new channel is created by invoking the {@link199* java.nio.channels.spi.SelectorProvider#openSocketChannel(ProtocolFamily)200* openSocketChannel(ProtocolFamily)} method of the system-wide default.201* {@link java.nio.channels.spi.SelectorProvider} object.</p>202*203* @param family204* The protocol family205*206* @return A new socket channel207*208* @throws UnsupportedOperationException209* If the specified protocol family is not supported. For example,210* suppose the parameter is specified as {@link211* java.net.StandardProtocolFamily#INET6 StandardProtocolFamily.INET6}212* but IPv6 is not enabled on the platform.213* @throws IOException214* If an I/O error occurs215*216* @see <a href="../../net/doc-files/net-properties.html#Ipv4IPv6">217* java.net.preferIPv4Stack</a> system property218*219* @since 15220*/221public static SocketChannel open(ProtocolFamily family) throws IOException {222return SelectorProvider.provider().openSocketChannel(requireNonNull(family));223}224225/**226* Opens a socket channel and connects it to a remote address.227*228* <p> If the remote address is an {@link InetSocketAddress} then this229* method works as if by invoking the {@link #open()} method, invoking the230* {@link #connect(SocketAddress) connect} method upon the resulting socket231* channel, passing it {@code remote}, and then returning that channel.232*233* <p> If the remote address is a {@link UnixDomainSocketAddress} then this234* works by invoking the {@link #open(ProtocolFamily)} method with {@link235* StandardProtocolFamily#UNIX} as parameter, invoking the {@link236* #connect(SocketAddress) connect} method upon the resulting socket channel,237* passing it {@code remote}, then returning that channel. </p>238*239* @param remote240* The remote address to which the new channel is to be connected241*242* @return A new, and connected, socket channel243*244* @throws AsynchronousCloseException245* If another thread closes this channel246* while the connect operation is in progress247*248* @throws ClosedByInterruptException249* If another thread interrupts the current thread250* while the connect operation is in progress, thereby251* closing the channel and setting the current thread's252* interrupt status253*254* @throws UnresolvedAddressException255* If the given remote address is an InetSocketAddress that is not fully256* resolved257*258* @throws UnsupportedAddressTypeException259* If the type of the given remote address is not supported260*261* @throws SecurityException262* If a security manager has been installed263* and it does not permit access to the given remote endpoint264*265* @throws IOException266* If some other I/O error occurs267*268* @see <a href="../../net/doc-files/net-properties.html#Ipv4IPv6">269* java.net.preferIPv4Stack</a> system property270*/271public static SocketChannel open(SocketAddress remote)272throws IOException273{274SocketChannel sc;275requireNonNull(remote);276if (remote instanceof InetSocketAddress)277sc = open();278else if (remote instanceof UnixDomainSocketAddress)279sc = open(StandardProtocolFamily.UNIX);280else281throw new UnsupportedAddressTypeException();282283try {284sc.connect(remote);285} catch (Throwable x) {286try {287sc.close();288} catch (Throwable suppressed) {289x.addSuppressed(suppressed);290}291throw x;292}293assert sc.isConnected();294return sc;295}296297/**298* Returns an operation set identifying this channel's supported299* operations.300*301* <p> Socket channels support connecting, reading, and writing, so this302* method returns {@code (}{@link SelectionKey#OP_CONNECT}303* {@code |} {@link SelectionKey#OP_READ} {@code |} {@link304* SelectionKey#OP_WRITE}{@code )}.305*306* @return The valid-operation set307*/308public final int validOps() {309return (SelectionKey.OP_READ310| SelectionKey.OP_WRITE311| SelectionKey.OP_CONNECT);312}313314315// -- Socket-specific operations --316317/**318* Binds the channel's socket to a local address.319*320* <p> This method is used to establish an association between the socket321* and a local address. For <i>Internet Protocol</i> sockets, once an322* association is established then the socket remains bound until the323* channel is closed. If the {@code local} parameter has the value {@code324* null} then the socket will be bound to an address that is assigned325* automatically.326*327* @apiNote328* Binding a socket channel to a <i>Unix Domain</i> socket creates a file329* corresponding to the file path in the {@link UnixDomainSocketAddress}. This330* file persists after the channel is closed, and must be removed before331* another socket can bind to the same name. If a socket channel to a Unix332* Domain socket is <i>implicitly</i> bound by connecting it without calling333* bind first, then its socket is334* <a href="../../../java/net/UnixDomainSocketAddress.html#unnamed">unnamed</a>335* with no corresponding socket file in the file-system. If a socket channel336* to a Unix Domain socket is <i>automatically</i> bound by calling {@code337* bind(null)} this results in an unnamed socket also.338*339* @implNote340* Each platform enforces an implementation specific maximum length for the341* name of a <i>Unix Domain</i> socket. This limitation is enforced when a342* channel is bound. The maximum length is typically close to and generally343* not less than 100 bytes.344*345* @param local The address to bind the socket, or {@code null} to bind346* the socket to an automatically assigned socket address347*348* @return This channel349*350* @throws ConnectionPendingException351* If a non-blocking connect operation is already in progress on352* this channel353* @throws AlreadyBoundException {@inheritDoc}354* @throws UnsupportedAddressTypeException {@inheritDoc}355* @throws ClosedChannelException {@inheritDoc}356* @throws IOException {@inheritDoc}357* @throws SecurityException358* If a security manager has been installed and its {@link359* SecurityManager#checkListen checkListen} method denies360* the operation for an <i>Internet protocol</i> socket address,361* or for a <i>Unix domain</i> socket address if it denies362* {@link NetPermission}{@code("accessUnixDomainSocket")}.363*364* @since 1.7365*/366@Override367public abstract SocketChannel bind(SocketAddress local)368throws IOException;369370/**371* @throws UnsupportedOperationException {@inheritDoc}372* @throws IllegalArgumentException {@inheritDoc}373* @throws ClosedChannelException {@inheritDoc}374* @throws IOException {@inheritDoc}375*376* @since 1.7377*/378@Override379public abstract <T> SocketChannel setOption(SocketOption<T> name, T value)380throws IOException;381382/**383* Shutdown the connection for reading without closing the channel.384*385* <p> Once shutdown for reading then further reads on the channel will386* return {@code -1}, the end-of-stream indication. If the input side of the387* connection is already shutdown then invoking this method has no effect.388*389* @return The channel390*391* @throws NotYetConnectedException392* If this channel is not yet connected393* @throws ClosedChannelException394* If this channel is closed395* @throws IOException396* If some other I/O error occurs397*398* @since 1.7399*/400public abstract SocketChannel shutdownInput() throws IOException;401402/**403* Shutdown the connection for writing without closing the channel.404*405* <p> Once shutdown for writing then further attempts to write to the406* channel will throw {@link ClosedChannelException}. If the output side of407* the connection is already shutdown then invoking this method has no408* effect.409*410* @return The channel411*412* @throws NotYetConnectedException413* If this channel is not yet connected414* @throws ClosedChannelException415* If this channel is closed416* @throws IOException417* If some other I/O error occurs418*419* @since 1.7420*/421public abstract SocketChannel shutdownOutput() throws IOException;422423/**424* Retrieves a socket associated with this channel.425*426* @return A socket associated with this channel427*428* @throws UnsupportedOperationException429* If the channel's socket is not an <i>Internet protocol</i> socket430*/431public abstract Socket socket();432433/**434* Tells whether or not this channel's network socket is connected.435*436* @return {@code true} if, and only if, this channel's network socket437* is {@link #isOpen open} and connected438*/439public abstract boolean isConnected();440441/**442* Tells whether or not a connection operation is in progress on this443* channel.444*445* @return {@code true} if, and only if, a connection operation has been446* initiated on this channel but not yet completed by invoking the447* {@link #finishConnect finishConnect} method448*/449public abstract boolean isConnectionPending();450451/**452* Connects this channel's socket.453*454* <p> If this channel is in non-blocking mode then an invocation of this455* method initiates a non-blocking connection operation. If the connection456* is established immediately, as can happen with a local connection, then457* this method returns {@code true}. Otherwise this method returns458* {@code false} and the connection operation must later be completed by459* invoking the {@link #finishConnect finishConnect} method.460*461* <p> If this channel is in blocking mode then an invocation of this462* method will block until the connection is established or an I/O error463* occurs.464*465* <p> For channels to <i>Internet protocol</i> sockets, this method performs466* exactly the same security checks as the {@link java.net.Socket} class.467* That is, if a security manager has been468* installed then this method verifies that its {@link469* java.lang.SecurityManager#checkConnect checkConnect} method permits470* connecting to the address and port number of the given remote endpoint.471*472* <p> For channels to <i>Unix Domain</i> sockets, this method checks473* {@link java.net.NetPermission NetPermission}{@code474* ("accessUnixDomainSocket")} with the security manager's {@link475* SecurityManager#checkPermission(java.security.Permission)476* checkPermission} method.477*478* <p> This method may be invoked at any time. If a read or write479* operation upon this channel is invoked while an invocation of this480* method is in progress then that operation will first block until this481* invocation is complete. If a connection attempt is initiated but fails,482* that is, if an invocation of this method throws a checked exception,483* then the channel will be closed. </p>484*485* @param remote486* The remote address to which this channel is to be connected487*488* @return {@code true} if a connection was established,489* {@code false} if this channel is in non-blocking mode490* and the connection operation is in progress491*492* @throws AlreadyConnectedException493* If this channel is already connected494*495* @throws ConnectionPendingException496* If a non-blocking connection operation is already in progress497* on this channel498*499* @throws ClosedChannelException500* If this channel is closed501*502* @throws AsynchronousCloseException503* If another thread closes this channel504* while the connect operation is in progress505*506* @throws ClosedByInterruptException507* If another thread interrupts the current thread508* while the connect operation is in progress, thereby509* closing the channel and setting the current thread's510* interrupt status511*512* @throws UnresolvedAddressException513* If the given remote address is an InetSocketAddress that is not fully resolved514*515* @throws UnsupportedAddressTypeException516* If the type of the given remote address is not supported517*518* @throws SecurityException519* If a security manager has been installed520* and it does not permit access to the given remote endpoint521*522* @throws IOException523* If some other I/O error occurs524*/525public abstract boolean connect(SocketAddress remote) throws IOException;526527/**528* Finishes the process of connecting a socket channel.529*530* <p> A non-blocking connection operation is initiated by placing a socket531* channel in non-blocking mode and then invoking its {@link #connect532* connect} method. Once the connection is established, or the attempt has533* failed, the socket channel will become connectable and this method may534* be invoked to complete the connection sequence. If the connection535* operation failed then invoking this method will cause an appropriate536* {@link java.io.IOException} to be thrown.537*538* <p> If this channel is already connected then this method will not block539* and will immediately return {@code true}. If this channel is in540* non-blocking mode then this method will return {@code false} if the541* connection process is not yet complete. If this channel is in blocking542* mode then this method will block until the connection either completes543* or fails, and will always either return {@code true} or throw a checked544* exception describing the failure.545*546* <p> This method may be invoked at any time. If a read or write547* operation upon this channel is invoked while an invocation of this548* method is in progress then that operation will first block until this549* invocation is complete. If a connection attempt fails, that is, if an550* invocation of this method throws a checked exception, then the channel551* will be closed. </p>552*553* @return {@code true} if, and only if, this channel's socket is now554* connected555*556* @throws NoConnectionPendingException557* If this channel is not connected and a connection operation558* has not been initiated559*560* @throws ClosedChannelException561* If this channel is closed562*563* @throws AsynchronousCloseException564* If another thread closes this channel565* while the connect operation is in progress566*567* @throws ClosedByInterruptException568* If another thread interrupts the current thread569* while the connect operation is in progress, thereby570* closing the channel and setting the current thread's571* interrupt status572*573* @throws IOException574* If some other I/O error occurs575*/576public abstract boolean finishConnect() throws IOException;577578/**579* Returns the remote address to which this channel's socket is connected.580*581* <p> Where the channel's socket is bound and connected to an <i>Internet582* Protocol</i> socket address then the return value is of type583* {@link java.net.InetSocketAddress}.584*585* <p> Where the channel's socket is bound and connected to a <i>Unix Domain</i>586* socket address, the returned address is a {@link UnixDomainSocketAddress}.587*588* @return The remote address; {@code null} if the channel's socket is not589* connected590*591* @throws ClosedChannelException592* If the channel is closed593* @throws IOException594* If an I/O error occurs595*596* @since 1.7597*/598public abstract SocketAddress getRemoteAddress() throws IOException;599600// -- ByteChannel operations --601602/**603* @throws NotYetConnectedException604* If this channel is not yet connected605*/606public abstract int read(ByteBuffer dst) throws IOException;607608/**609* @throws NotYetConnectedException610* If this channel is not yet connected611*/612public abstract long read(ByteBuffer[] dsts, int offset, int length)613throws IOException;614615/**616* @throws NotYetConnectedException617* If this channel is not yet connected618*/619public final long read(ByteBuffer[] dsts) throws IOException {620return read(dsts, 0, dsts.length);621}622623/**624* @throws NotYetConnectedException625* If this channel is not yet connected626*/627public abstract int write(ByteBuffer src) throws IOException;628629/**630* @throws NotYetConnectedException631* If this channel is not yet connected632*/633public abstract long write(ByteBuffer[] srcs, int offset, int length)634throws IOException;635636/**637* @throws NotYetConnectedException638* If this channel is not yet connected639*/640public final long write(ByteBuffer[] srcs) throws IOException {641return write(srcs, 0, srcs.length);642}643644/**645* {@inheritDoc}646*647* If there is a security manager set, its {@code checkConnect} method is648* called with the local address and {@code -1} as its arguments to see649* if the operation is allowed. If the operation is not allowed,650* a {@code SocketAddress} representing the651* {@link java.net.InetAddress#getLoopbackAddress loopback} address and the652* local port of the channel's socket is returned.653*654* <p> Where the channel is bound to a Unix Domain socket address, the socket655* address is a {@link UnixDomainSocketAddress}. If there is a security manager656* set, its {@link SecurityManager#checkPermission(java.security.Permission)657* checkPermission} method is called with {@link NetPermission}{@code658* ("accessUnixDomainSocket")}. If the operation is not allowed an unnamed659* {@link UnixDomainSocketAddress} is returned.660*661* @return The {@code SocketAddress} that the socket is bound to, or the662* {@code SocketAddress} representing the loopback address or empty663* path if denied by the security manager, or {@code null} if the664* channel's socket is not bound665*666* @throws ClosedChannelException {@inheritDoc}667* @throws IOException {@inheritDoc}668*/669@Override670public abstract SocketAddress getLocalAddress() throws IOException;671}672673674