Path: blob/master/src/java.base/share/classes/java/nio/channels/AsynchronousSocketChannel.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.util.concurrent.TimeUnit;29import java.util.concurrent.Future;30import java.io.IOException;31import java.net.SocketOption;32import java.net.SocketAddress;33import java.nio.ByteBuffer;3435/**36* An asynchronous channel for stream-oriented connecting sockets.37*38* <p> Asynchronous socket channels are created in one of two ways. A newly-created39* {@code AsynchronousSocketChannel} is created by invoking one of the {@link40* #open open} methods defined by this class. A newly-created channel is open but41* not yet connected. A connected {@code AsynchronousSocketChannel} is created42* when a connection is made to the socket of an {@link AsynchronousServerSocketChannel}.43* It is not possible to create an asynchronous socket channel for an arbitrary,44* pre-existing {@link java.net.Socket socket}.45*46* <p> A newly-created channel is connected by invoking its {@link #connect connect}47* method; once connected, a channel remains connected until it is closed. Whether48* or not a socket channel is connected may be determined by invoking its {@link49* #getRemoteAddress getRemoteAddress} method. An attempt to invoke an I/O50* operation upon an unconnected channel will cause a {@link NotYetConnectedException}51* to be thrown.52*53* <p> Channels of this type are safe for use by multiple concurrent threads.54* They support concurrent reading and writing, though at most one read operation55* and one write operation can be outstanding at any time.56* If a thread initiates a read operation before a previous read operation has57* completed then a {@link ReadPendingException} will be thrown. Similarly, an58* attempt to initiate a write operation before a previous write has completed59* will throw a {@link WritePendingException}.60*61* <p> Socket options are configured using the {@link #setOption(SocketOption,Object)62* setOption} method. Asynchronous socket channels support the following options:63* <blockquote>64* <table class="striped">65* <caption style="display:none">Socket options</caption>66* <thead>67* <tr>68* <th scope="col">Option Name</th>69* <th scope="col">Description</th>70* </tr>71* </thead>72* <tbody>73* <tr>74* <th scope="row"> {@link java.net.StandardSocketOptions#SO_SNDBUF SO_SNDBUF} </th>75* <td> The size of the socket send buffer </td>76* </tr>77* <tr>78* <th scope="row"> {@link java.net.StandardSocketOptions#SO_RCVBUF SO_RCVBUF} </th>79* <td> The size of the socket receive buffer </td>80* </tr>81* <tr>82* <th scope="row"> {@link java.net.StandardSocketOptions#SO_KEEPALIVE SO_KEEPALIVE} </th>83* <td> Keep connection alive </td>84* </tr>85* <tr>86* <th scope="row"> {@link java.net.StandardSocketOptions#SO_REUSEADDR SO_REUSEADDR} </th>87* <td> Re-use address </td>88* </tr>89* <tr>90* <th scope="row"> {@link java.net.StandardSocketOptions#TCP_NODELAY TCP_NODELAY} </th>91* <td> Disable the Nagle algorithm </td>92* </tr>93* </tbody>94* </table>95* </blockquote>96* Additional (implementation specific) options may also be supported.97*98* <h2>Timeouts</h2>99*100* <p> The {@link #read(ByteBuffer,long,TimeUnit,Object,CompletionHandler) read}101* and {@link #write(ByteBuffer,long,TimeUnit,Object,CompletionHandler) write}102* methods defined by this class allow a timeout to be specified when initiating103* a read or write operation. If the timeout elapses before an operation completes104* then the operation completes with the exception {@link105* InterruptedByTimeoutException}. A timeout may leave the channel, or the106* underlying connection, in an inconsistent state. Where the implementation107* cannot guarantee that bytes have not been read from the channel then it puts108* the channel into an implementation specific <em>error state</em>. A subsequent109* attempt to initiate a {@code read} operation causes an unspecified runtime110* exception to be thrown. Similarly if a {@code write} operation times out and111* the implementation cannot guarantee bytes have not been written to the112* channel then further attempts to {@code write} to the channel cause an113* unspecified runtime exception to be thrown. When a timeout elapses then the114* state of the {@link ByteBuffer}, or the sequence of buffers, for the I/O115* operation is not defined. Buffers should be discarded or at least care must116* be taken to ensure that the buffers are not accessed while the channel remains117* open. All methods that accept timeout parameters treat values less than or118* equal to zero to mean that the I/O operation does not timeout.119*120* @since 1.7121*/122123public abstract class AsynchronousSocketChannel124implements AsynchronousByteChannel, NetworkChannel125{126private final AsynchronousChannelProvider provider;127128/**129* Initializes a new instance of this class.130*131* @param provider132* The provider that created this channel133*/134protected AsynchronousSocketChannel(AsynchronousChannelProvider provider) {135this.provider = provider;136}137138/**139* Returns the provider that created this channel.140*141* @return The provider that created this channel142*/143public final AsynchronousChannelProvider provider() {144return provider;145}146147/**148* Opens an asynchronous socket channel.149*150* <p> The new channel is created by invoking the {@link151* AsynchronousChannelProvider#openAsynchronousSocketChannel152* openAsynchronousSocketChannel} method on the {@link153* AsynchronousChannelProvider} that created the group. If the group parameter154* is {@code null} then the resulting channel is created by the system-wide155* default provider, and bound to the <em>default group</em>.156*157* @param group158* The group to which the newly constructed channel should be bound,159* or {@code null} for the default group160*161* @return A new asynchronous socket channel162*163* @throws ShutdownChannelGroupException164* If the channel group is shutdown165* @throws IOException166* If an I/O error occurs167*/168public static AsynchronousSocketChannel open(AsynchronousChannelGroup group)169throws IOException170{171AsynchronousChannelProvider provider = (group == null) ?172AsynchronousChannelProvider.provider() : group.provider();173return provider.openAsynchronousSocketChannel(group);174}175176/**177* Opens an asynchronous socket channel.178*179* <p> This method returns an asynchronous socket channel that is bound to180* the <em>default group</em>.This method is equivalent to evaluating the181* expression:182* <blockquote><pre>183* open((AsynchronousChannelGroup)null);184* </pre></blockquote>185*186* @return A new asynchronous socket channel187*188* @throws IOException189* If an I/O error occurs190*/191public static AsynchronousSocketChannel open()192throws IOException193{194return open(null);195}196197198// -- socket options and related --199200/**201* @throws ConnectionPendingException202* If a connection operation is already in progress on this channel203* @throws AlreadyBoundException {@inheritDoc}204* @throws UnsupportedAddressTypeException {@inheritDoc}205* @throws ClosedChannelException {@inheritDoc}206* @throws IOException {@inheritDoc}207* @throws SecurityException208* If a security manager has been installed and its209* {@link SecurityManager#checkListen checkListen} method denies210* the operation211*/212@Override213public abstract AsynchronousSocketChannel bind(SocketAddress local)214throws IOException;215216/**217* @throws IllegalArgumentException {@inheritDoc}218* @throws ClosedChannelException {@inheritDoc}219* @throws IOException {@inheritDoc}220*/221@Override222public abstract <T> AsynchronousSocketChannel setOption(SocketOption<T> name, T value)223throws IOException;224225/**226* Shutdown the connection for reading without closing the channel.227*228* <p> Once shutdown for reading then further reads on the channel will229* return {@code -1}, the end-of-stream indication. If the input side of the230* connection is already shutdown then invoking this method has no effect.231* The effect on an outstanding read operation is system dependent and232* therefore not specified. The effect, if any, when there is data in the233* socket receive buffer that has not been read, or data arrives subsequently,234* is also system dependent.235*236* @return The channel237*238* @throws NotYetConnectedException239* If this channel is not yet connected240* @throws ClosedChannelException241* If this channel is closed242* @throws IOException243* If some other I/O error occurs244*/245public abstract AsynchronousSocketChannel shutdownInput() throws IOException;246247/**248* Shutdown the connection for writing without closing the channel.249*250* <p> Once shutdown for writing then further attempts to write to the251* channel will throw {@link ClosedChannelException}. If the output side of252* the connection is already shutdown then invoking this method has no253* effect. The effect on an outstanding write operation is system dependent254* and therefore not specified.255*256* @return The channel257*258* @throws NotYetConnectedException259* If this channel is not yet connected260* @throws ClosedChannelException261* If this channel is closed262* @throws IOException263* If some other I/O error occurs264*/265public abstract AsynchronousSocketChannel shutdownOutput() throws IOException;266267// -- state --268269/**270* Returns the remote address to which this channel's socket is connected.271*272* <p> Where the channel is bound and connected to an Internet Protocol273* socket address then the return value from this method is of type {@link274* java.net.InetSocketAddress}.275*276* @return The remote address; {@code null} if the channel's socket is not277* connected278*279* @throws ClosedChannelException280* If the channel is closed281* @throws IOException282* If an I/O error occurs283*/284public abstract SocketAddress getRemoteAddress() throws IOException;285286// -- asynchronous operations --287288/**289* Connects this channel.290*291* <p> This method initiates an operation to connect this channel. The292* {@code handler} parameter is a completion handler that is invoked when293* the connection is successfully established or connection cannot be294* established. If the connection cannot be established then the channel is295* closed.296*297* <p> This method performs exactly the same security checks as the {@link298* java.net.Socket} class. That is, if a security manager has been299* installed then this method verifies that its {@link300* java.lang.SecurityManager#checkConnect checkConnect} method permits301* connecting to the address and port number of the given remote endpoint.302*303* @param <A>304* The type of the attachment305* @param remote306* The remote address to which this channel is to be connected307* @param attachment308* The object to attach to the I/O operation; can be {@code null}309* @param handler310* The handler for consuming the result311*312* @throws UnresolvedAddressException313* If the given remote address is not fully resolved314* @throws UnsupportedAddressTypeException315* If the type of the given remote address is not supported316* @throws AlreadyConnectedException317* If this channel is already connected318* @throws ConnectionPendingException319* If a connection operation is already in progress on this channel320* @throws ShutdownChannelGroupException321* If the channel group has terminated322* @throws SecurityException323* If a security manager has been installed324* and it does not permit access to the given remote endpoint325*326* @see #getRemoteAddress327*/328public abstract <A> void connect(SocketAddress remote,329A attachment,330CompletionHandler<Void,? super A> handler);331332/**333* Connects this channel.334*335* <p> This method initiates an operation to connect this channel. This336* method behaves in exactly the same manner as the {@link337* #connect(SocketAddress, Object, CompletionHandler)} method except that338* instead of specifying a completion handler, this method returns a {@code339* Future} representing the pending result. The {@code Future}'s {@link340* Future#get() get} method returns {@code null} on successful completion.341*342* @param remote343* The remote address to which this channel is to be connected344*345* @return A {@code Future} object representing the pending result346*347* @throws UnresolvedAddressException348* If the given remote address is not fully resolved349* @throws UnsupportedAddressTypeException350* If the type of the given remote address is not supported351* @throws AlreadyConnectedException352* If this channel is already connected353* @throws ConnectionPendingException354* If a connection operation is already in progress on this channel355* @throws SecurityException356* If a security manager has been installed357* and it does not permit access to the given remote endpoint358*/359public abstract Future<Void> connect(SocketAddress remote);360361/**362* Reads a sequence of bytes from this channel into the given buffer.363*364* <p> This method initiates an asynchronous read operation to read a365* sequence of bytes from this channel into the given buffer. The {@code366* handler} parameter is a completion handler that is invoked when the read367* operation completes (or fails). The result passed to the completion368* handler is the number of bytes read or {@code -1} if no bytes could be369* read because the channel has reached end-of-stream.370*371* <p> If a timeout is specified and the timeout elapses before the operation372* completes then the operation completes with the exception {@link373* InterruptedByTimeoutException}. Where a timeout occurs, and the374* implementation cannot guarantee that bytes have not been read, or will not375* be read from the channel into the given buffer, then further attempts to376* read from the channel will cause an unspecific runtime exception to be377* thrown.378*379* <p> Otherwise this method works in the same manner as the {@link380* AsynchronousByteChannel#read(ByteBuffer,Object,CompletionHandler)}381* method.382*383* @param <A>384* The type of the attachment385* @param dst386* The buffer into which bytes are to be transferred387* @param timeout388* The maximum time for the I/O operation to complete389* @param unit390* The time unit of the {@code timeout} argument391* @param attachment392* The object to attach to the I/O operation; can be {@code null}393* @param handler394* The handler for consuming the result395*396* @throws IllegalArgumentException397* If the buffer is read-only398* @throws ReadPendingException399* If a read operation is already in progress on this channel400* @throws NotYetConnectedException401* If this channel is not yet connected402* @throws ShutdownChannelGroupException403* If the channel group has terminated404*/405public abstract <A> void read(ByteBuffer dst,406long timeout,407TimeUnit unit,408A attachment,409CompletionHandler<Integer,? super A> handler);410411/**412* @throws IllegalArgumentException {@inheritDoc}413* @throws ReadPendingException {@inheritDoc}414* @throws NotYetConnectedException415* If this channel is not yet connected416* @throws ShutdownChannelGroupException417* If the channel group has terminated418*/419@Override420public final <A> void read(ByteBuffer dst,421A attachment,422CompletionHandler<Integer,? super A> handler)423{424read(dst, 0L, TimeUnit.MILLISECONDS, attachment, handler);425}426427/**428* @throws IllegalArgumentException {@inheritDoc}429* @throws ReadPendingException {@inheritDoc}430* @throws NotYetConnectedException431* If this channel is not yet connected432*/433@Override434public abstract Future<Integer> read(ByteBuffer dst);435436/**437* Reads a sequence of bytes from this channel into a subsequence of the438* given buffers. This operation, sometimes called a <em>scattering read</em>,439* is often useful when implementing network protocols that group data into440* segments consisting of one or more fixed-length headers followed by a441* variable-length body. The {@code handler} parameter is a completion442* handler that is invoked when the read operation completes (or fails). The443* result passed to the completion handler is the number of bytes read or444* {@code -1} if no bytes could be read because the channel has reached445* end-of-stream.446*447* <p> This method initiates a read of up to <i>r</i> bytes from this channel,448* where <i>r</i> is the total number of bytes remaining in the specified449* subsequence of the given buffer array, that is,450*451* <blockquote><pre>452* dsts[offset].remaining()453* + dsts[offset+1].remaining()454* + ... + dsts[offset+length-1].remaining()</pre></blockquote>455*456* at the moment that the read is attempted.457*458* <p> Suppose that a byte sequence of length <i>n</i> is read, where459* {@code 0} {@code <} <i>n</i> {@code <=} <i>r</i>.460* Up to the first {@code dsts[offset].remaining()} bytes of this sequence461* are transferred into buffer {@code dsts[offset]}, up to the next462* {@code dsts[offset+1].remaining()} bytes are transferred into buffer463* {@code dsts[offset+1]}, and so forth, until the entire byte sequence464* is transferred into the given buffers. As many bytes as possible are465* transferred into each buffer, hence the final position of each updated466* buffer, except the last updated buffer, is guaranteed to be equal to467* that buffer's limit. The underlying operating system may impose a limit468* on the number of buffers that may be used in an I/O operation. Where the469* number of buffers (with bytes remaining), exceeds this limit, then the470* I/O operation is performed with the maximum number of buffers allowed by471* the operating system.472*473* <p> If a timeout is specified and the timeout elapses before the operation474* completes then it completes with the exception {@link475* InterruptedByTimeoutException}. Where a timeout occurs, and the476* implementation cannot guarantee that bytes have not been read, or will not477* be read from the channel into the given buffers, then further attempts to478* read from the channel will cause an unspecific runtime exception to be479* thrown.480*481* @param <A>482* The type of the attachment483* @param dsts484* The buffers into which bytes are to be transferred485* @param offset486* The offset within the buffer array of the first buffer into which487* bytes are to be transferred; must be non-negative and no larger than488* {@code dsts.length}489* @param length490* The maximum number of buffers to be accessed; must be non-negative491* and no larger than {@code dsts.length - offset}492* @param timeout493* The maximum time for the I/O operation to complete494* @param unit495* The time unit of the {@code timeout} argument496* @param attachment497* The object to attach to the I/O operation; can be {@code null}498* @param handler499* The handler for consuming the result500*501* @throws IndexOutOfBoundsException502* If the pre-conditions for the {@code offset} and {@code length}503* parameter aren't met504* @throws IllegalArgumentException505* If the buffer is read-only506* @throws ReadPendingException507* If a read operation is already in progress on this channel508* @throws NotYetConnectedException509* If this channel is not yet connected510* @throws ShutdownChannelGroupException511* If the channel group has terminated512*/513public abstract <A> void read(ByteBuffer[] dsts,514int offset,515int length,516long timeout,517TimeUnit unit,518A attachment,519CompletionHandler<Long,? super A> handler);520521/**522* Writes a sequence of bytes to this channel from the given buffer.523*524* <p> This method initiates an asynchronous write operation to write a525* sequence of bytes to this channel from the given buffer. The {@code526* handler} parameter is a completion handler that is invoked when the write527* operation completes (or fails). The result passed to the completion528* handler is the number of bytes written.529*530* <p> If a timeout is specified and the timeout elapses before the operation531* completes then it completes with the exception {@link532* InterruptedByTimeoutException}. Where a timeout occurs, and the533* implementation cannot guarantee that bytes have not been written, or will534* not be written to the channel from the given buffer, then further attempts535* to write to the channel will cause an unspecific runtime exception to be536* thrown.537*538* <p> Otherwise this method works in the same manner as the {@link539* AsynchronousByteChannel#write(ByteBuffer,Object,CompletionHandler)}540* method.541*542* @param <A>543* The type of the attachment544* @param src545* The buffer from which bytes are to be retrieved546* @param timeout547* The maximum time for the I/O operation to complete548* @param unit549* The time unit of the {@code timeout} argument550* @param attachment551* The object to attach to the I/O operation; can be {@code null}552* @param handler553* The handler for consuming the result554*555* @throws WritePendingException556* If a write operation is already in progress on this channel557* @throws NotYetConnectedException558* If this channel is not yet connected559* @throws ShutdownChannelGroupException560* If the channel group has terminated561*/562public abstract <A> void write(ByteBuffer src,563long timeout,564TimeUnit unit,565A attachment,566CompletionHandler<Integer,? super A> handler);567568/**569* @throws WritePendingException {@inheritDoc}570* @throws NotYetConnectedException571* If this channel is not yet connected572* @throws ShutdownChannelGroupException573* If the channel group has terminated574*/575@Override576public final <A> void write(ByteBuffer src,577A attachment,578CompletionHandler<Integer,? super A> handler)579580{581write(src, 0L, TimeUnit.MILLISECONDS, attachment, handler);582}583584/**585* @throws WritePendingException {@inheritDoc}586* @throws NotYetConnectedException587* If this channel is not yet connected588*/589@Override590public abstract Future<Integer> write(ByteBuffer src);591592/**593* Writes a sequence of bytes to this channel from a subsequence of the given594* buffers. This operation, sometimes called a <em>gathering write</em>, is595* often useful when implementing network protocols that group data into596* segments consisting of one or more fixed-length headers followed by a597* variable-length body. The {@code handler} parameter is a completion598* handler that is invoked when the write operation completes (or fails).599* The result passed to the completion handler is the number of bytes written.600*601* <p> This method initiates a write of up to <i>r</i> bytes to this channel,602* where <i>r</i> is the total number of bytes remaining in the specified603* subsequence of the given buffer array, that is,604*605* <blockquote><pre>606* srcs[offset].remaining()607* + srcs[offset+1].remaining()608* + ... + srcs[offset+length-1].remaining()</pre></blockquote>609*610* at the moment that the write is attempted.611*612* <p> Suppose that a byte sequence of length <i>n</i> is written, where613* {@code 0} {@code <} <i>n</i> {@code <=} <i>r</i>.614* Up to the first {@code srcs[offset].remaining()} bytes of this sequence615* are written from buffer {@code srcs[offset]}, up to the next616* {@code srcs[offset+1].remaining()} bytes are written from buffer617* {@code srcs[offset+1]}, and so forth, until the entire byte sequence is618* written. As many bytes as possible are written from each buffer, hence619* the final position of each updated buffer, except the last updated620* buffer, is guaranteed to be equal to that buffer's limit. The underlying621* operating system may impose a limit on the number of buffers that may be622* used in an I/O operation. Where the number of buffers (with bytes623* remaining), exceeds this limit, then the I/O operation is performed with624* the maximum number of buffers allowed by the operating system.625*626* <p> If a timeout is specified and the timeout elapses before the operation627* completes then it completes with the exception {@link628* InterruptedByTimeoutException}. Where a timeout occurs, and the629* implementation cannot guarantee that bytes have not been written, or will630* not be written to the channel from the given buffers, then further attempts631* to write to the channel will cause an unspecific runtime exception to be632* thrown.633*634* @param <A>635* The type of the attachment636* @param srcs637* The buffers from which bytes are to be retrieved638* @param offset639* The offset within the buffer array of the first buffer from which640* bytes are to be retrieved; must be non-negative and no larger641* than {@code srcs.length}642* @param length643* The maximum number of buffers to be accessed; must be non-negative644* and no larger than {@code srcs.length - offset}645* @param timeout646* The maximum time for the I/O operation to complete647* @param unit648* The time unit of the {@code timeout} argument649* @param attachment650* The object to attach to the I/O operation; can be {@code null}651* @param handler652* The handler for consuming the result653*654* @throws IndexOutOfBoundsException655* If the pre-conditions for the {@code offset} and {@code length}656* parameter aren't met657* @throws WritePendingException658* If a write operation is already in progress on this channel659* @throws NotYetConnectedException660* If this channel is not yet connected661* @throws ShutdownChannelGroupException662* If the channel group has terminated663*/664public abstract <A> void write(ByteBuffer[] srcs,665int offset,666int length,667long timeout,668TimeUnit unit,669A attachment,670CompletionHandler<Long,? super A> handler);671672/**673* {@inheritDoc}674* <p>675* If there is a security manager set, its {@code checkConnect} method is676* called with the local address and {@code -1} as its arguments to see677* if the operation is allowed. If the operation is not allowed,678* a {@code SocketAddress} representing the679* {@link java.net.InetAddress#getLoopbackAddress loopback} address and the680* local port of the channel's socket is returned.681*682* @return The {@code SocketAddress} that the socket is bound to, or the683* {@code SocketAddress} representing the loopback address if684* denied by the security manager, or {@code null} if the685* channel's socket is not bound686*687* @throws ClosedChannelException {@inheritDoc}688* @throws IOException {@inheritDoc}689*/690public abstract SocketAddress getLocalAddress() throws IOException;691}692693694