Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/src/share/classes/java/nio/channels/AsynchronousSocketChannel.java
38918 views
/*1* Copyright (c) 2007, 2013, 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 border summary="Socket options">65* <tr>66* <th>Option Name</th>67* <th>Description</th>68* </tr>69* <tr>70* <td> {@link java.net.StandardSocketOptions#SO_SNDBUF SO_SNDBUF} </td>71* <td> The size of the socket send buffer </td>72* </tr>73* <tr>74* <td> {@link java.net.StandardSocketOptions#SO_RCVBUF SO_RCVBUF} </td>75* <td> The size of the socket receive buffer </td>76* </tr>77* <tr>78* <td> {@link java.net.StandardSocketOptions#SO_KEEPALIVE SO_KEEPALIVE} </td>79* <td> Keep connection alive </td>80* </tr>81* <tr>82* <td> {@link java.net.StandardSocketOptions#SO_REUSEADDR SO_REUSEADDR} </td>83* <td> Re-use address </td>84* </tr>85* <tr>86* <td> {@link java.net.StandardSocketOptions#TCP_NODELAY TCP_NODELAY} </td>87* <td> Disable the Nagle algorithm </td>88* </tr>89* </table>90* </blockquote>91* Additional (implementation specific) options may also be supported.92*93* <h2>Timeouts</h2>94*95* <p> The {@link #read(ByteBuffer,long,TimeUnit,Object,CompletionHandler) read}96* and {@link #write(ByteBuffer,long,TimeUnit,Object,CompletionHandler) write}97* methods defined by this class allow a timeout to be specified when initiating98* a read or write operation. If the timeout elapses before an operation completes99* then the operation completes with the exception {@link100* InterruptedByTimeoutException}. A timeout may leave the channel, or the101* underlying connection, in an inconsistent state. Where the implementation102* cannot guarantee that bytes have not been read from the channel then it puts103* the channel into an implementation specific <em>error state</em>. A subsequent104* attempt to initiate a {@code read} operation causes an unspecified runtime105* exception to be thrown. Similarly if a {@code write} operation times out and106* the implementation cannot guarantee bytes have not been written to the107* channel then further attempts to {@code write} to the channel cause an108* unspecified runtime exception to be thrown. When a timeout elapses then the109* state of the {@link ByteBuffer}, or the sequence of buffers, for the I/O110* operation is not defined. Buffers should be discarded or at least care must111* be taken to ensure that the buffers are not accessed while the channel remains112* open. All methods that accept timeout parameters treat values less than or113* equal to zero to mean that the I/O operation does not timeout.114*115* @since 1.7116*/117118public abstract class AsynchronousSocketChannel119implements AsynchronousByteChannel, NetworkChannel120{121private final AsynchronousChannelProvider provider;122123/**124* Initializes a new instance of this class.125*126* @param provider127* The provider that created this channel128*/129protected AsynchronousSocketChannel(AsynchronousChannelProvider provider) {130this.provider = provider;131}132133/**134* Returns the provider that created this channel.135*136* @return The provider that created this channel137*/138public final AsynchronousChannelProvider provider() {139return provider;140}141142/**143* Opens an asynchronous socket channel.144*145* <p> The new channel is created by invoking the {@link146* AsynchronousChannelProvider#openAsynchronousSocketChannel147* openAsynchronousSocketChannel} method on the {@link148* AsynchronousChannelProvider} that created the group. If the group parameter149* is {@code null} then the resulting channel is created by the system-wide150* default provider, and bound to the <em>default group</em>.151*152* @param group153* The group to which the newly constructed channel should be bound,154* or {@code null} for the default group155*156* @return A new asynchronous socket channel157*158* @throws ShutdownChannelGroupException159* If the channel group is shutdown160* @throws IOException161* If an I/O error occurs162*/163public static AsynchronousSocketChannel open(AsynchronousChannelGroup group)164throws IOException165{166AsynchronousChannelProvider provider = (group == null) ?167AsynchronousChannelProvider.provider() : group.provider();168return provider.openAsynchronousSocketChannel(group);169}170171/**172* Opens an asynchronous socket channel.173*174* <p> This method returns an asynchronous socket channel that is bound to175* the <em>default group</em>.This method is equivalent to evaluating the176* expression:177* <blockquote><pre>178* open((AsynchronousChannelGroup)null);179* </pre></blockquote>180*181* @return A new asynchronous socket channel182*183* @throws IOException184* If an I/O error occurs185*/186public static AsynchronousSocketChannel open()187throws IOException188{189return open(null);190}191192193// -- socket options and related --194195/**196* @throws ConnectionPendingException197* If a connection operation is already in progress on this channel198* @throws AlreadyBoundException {@inheritDoc}199* @throws UnsupportedAddressTypeException {@inheritDoc}200* @throws ClosedChannelException {@inheritDoc}201* @throws IOException {@inheritDoc}202* @throws SecurityException203* If a security manager has been installed and its204* {@link SecurityManager#checkListen checkListen} method denies205* the operation206*/207@Override208public abstract AsynchronousSocketChannel bind(SocketAddress local)209throws IOException;210211/**212* @throws IllegalArgumentException {@inheritDoc}213* @throws ClosedChannelException {@inheritDoc}214* @throws IOException {@inheritDoc}215*/216@Override217public abstract <T> AsynchronousSocketChannel setOption(SocketOption<T> name, T value)218throws IOException;219220/**221* Shutdown the connection for reading without closing the channel.222*223* <p> Once shutdown for reading then further reads on the channel will224* return {@code -1}, the end-of-stream indication. If the input side of the225* connection is already shutdown then invoking this method has no effect.226* The effect on an outstanding read operation is system dependent and227* therefore not specified. The effect, if any, when there is data in the228* socket receive buffer that has not been read, or data arrives subsequently,229* is also system dependent.230*231* @return The channel232*233* @throws NotYetConnectedException234* If this channel is not yet connected235* @throws ClosedChannelException236* If this channel is closed237* @throws IOException238* If some other I/O error occurs239*/240public abstract AsynchronousSocketChannel shutdownInput() throws IOException;241242/**243* Shutdown the connection for writing without closing the channel.244*245* <p> Once shutdown for writing then further attempts to write to the246* channel will throw {@link ClosedChannelException}. If the output side of247* the connection is already shutdown then invoking this method has no248* effect. The effect on an outstanding write operation is system dependent249* and therefore not specified.250*251* @return The channel252*253* @throws NotYetConnectedException254* If this channel is not yet connected255* @throws ClosedChannelException256* If this channel is closed257* @throws IOException258* If some other I/O error occurs259*/260public abstract AsynchronousSocketChannel shutdownOutput() throws IOException;261262// -- state --263264/**265* Returns the remote address to which this channel's socket is connected.266*267* <p> Where the channel is bound and connected to an Internet Protocol268* socket address then the return value from this method is of type {@link269* java.net.InetSocketAddress}.270*271* @return The remote address; {@code null} if the channel's socket is not272* connected273*274* @throws ClosedChannelException275* If the channel is closed276* @throws IOException277* If an I/O error occurs278*/279public abstract SocketAddress getRemoteAddress() throws IOException;280281// -- asynchronous operations --282283/**284* Connects this channel.285*286* <p> This method initiates an operation to connect this channel. The287* {@code handler} parameter is a completion handler that is invoked when288* the connection is successfully established or connection cannot be289* established. If the connection cannot be established then the channel is290* closed.291*292* <p> This method performs exactly the same security checks as the {@link293* java.net.Socket} class. That is, if a security manager has been294* installed then this method verifies that its {@link295* java.lang.SecurityManager#checkConnect checkConnect} method permits296* connecting to the address and port number of the given remote endpoint.297*298* @param <A>299* The type of the attachment300* @param remote301* The remote address to which this channel is to be connected302* @param attachment303* The object to attach to the I/O operation; can be {@code null}304* @param handler305* The handler for consuming the result306*307* @throws UnresolvedAddressException308* If the given remote address is not fully resolved309* @throws UnsupportedAddressTypeException310* If the type of the given remote address is not supported311* @throws AlreadyConnectedException312* If this channel is already connected313* @throws ConnectionPendingException314* If a connection operation is already in progress on this channel315* @throws ShutdownChannelGroupException316* If the channel group has terminated317* @throws SecurityException318* If a security manager has been installed319* and it does not permit access to the given remote endpoint320*321* @see #getRemoteAddress322*/323public abstract <A> void connect(SocketAddress remote,324A attachment,325CompletionHandler<Void,? super A> handler);326327/**328* Connects this channel.329*330* <p> This method initiates an operation to connect this channel. This331* method behaves in exactly the same manner as the {@link332* #connect(SocketAddress, Object, CompletionHandler)} method except that333* instead of specifying a completion handler, this method returns a {@code334* Future} representing the pending result. The {@code Future}'s {@link335* Future#get() get} method returns {@code null} on successful completion.336*337* @param remote338* The remote address to which this channel is to be connected339*340* @return A {@code Future} object representing the pending result341*342* @throws UnresolvedAddressException343* If the given remote address is not fully resolved344* @throws UnsupportedAddressTypeException345* If the type of the given remote address is not supported346* @throws AlreadyConnectedException347* If this channel is already connected348* @throws ConnectionPendingException349* If a connection operation is already in progress on this channel350* @throws SecurityException351* If a security manager has been installed352* and it does not permit access to the given remote endpoint353*/354public abstract Future<Void> connect(SocketAddress remote);355356/**357* Reads a sequence of bytes from this channel into the given buffer.358*359* <p> This method initiates an asynchronous read operation to read a360* sequence of bytes from this channel into the given buffer. The {@code361* handler} parameter is a completion handler that is invoked when the read362* operation completes (or fails). The result passed to the completion363* handler is the number of bytes read or {@code -1} if no bytes could be364* read because the channel has reached end-of-stream.365*366* <p> If a timeout is specified and the timeout elapses before the operation367* completes then the operation completes with the exception {@link368* InterruptedByTimeoutException}. Where a timeout occurs, and the369* implementation cannot guarantee that bytes have not been read, or will not370* be read from the channel into the given buffer, then further attempts to371* read from the channel will cause an unspecific runtime exception to be372* thrown.373*374* <p> Otherwise this method works in the same manner as the {@link375* AsynchronousByteChannel#read(ByteBuffer,Object,CompletionHandler)}376* method.377*378* @param <A>379* The type of the attachment380* @param dst381* The buffer into which bytes are to be transferred382* @param timeout383* The maximum time for the I/O operation to complete384* @param unit385* The time unit of the {@code timeout} argument386* @param attachment387* The object to attach to the I/O operation; can be {@code null}388* @param handler389* The handler for consuming the result390*391* @throws IllegalArgumentException392* If the buffer is read-only393* @throws ReadPendingException394* If a read operation is already in progress on this channel395* @throws NotYetConnectedException396* If this channel is not yet connected397* @throws ShutdownChannelGroupException398* If the channel group has terminated399*/400public abstract <A> void read(ByteBuffer dst,401long timeout,402TimeUnit unit,403A attachment,404CompletionHandler<Integer,? super A> handler);405406/**407* @throws IllegalArgumentException {@inheritDoc}408* @throws ReadPendingException {@inheritDoc}409* @throws NotYetConnectedException410* If this channel is not yet connected411* @throws ShutdownChannelGroupException412* If the channel group has terminated413*/414@Override415public final <A> void read(ByteBuffer dst,416A attachment,417CompletionHandler<Integer,? super A> handler)418{419read(dst, 0L, TimeUnit.MILLISECONDS, attachment, handler);420}421422/**423* @throws IllegalArgumentException {@inheritDoc}424* @throws ReadPendingException {@inheritDoc}425* @throws NotYetConnectedException426* If this channel is not yet connected427*/428@Override429public abstract Future<Integer> read(ByteBuffer dst);430431/**432* Reads a sequence of bytes from this channel into a subsequence of the433* given buffers. This operation, sometimes called a <em>scattering read</em>,434* is often useful when implementing network protocols that group data into435* segments consisting of one or more fixed-length headers followed by a436* variable-length body. The {@code handler} parameter is a completion437* handler that is invoked when the read operation completes (or fails). The438* result passed to the completion handler is the number of bytes read or439* {@code -1} if no bytes could be read because the channel has reached440* end-of-stream.441*442* <p> This method initiates a read of up to <i>r</i> bytes from this channel,443* where <i>r</i> is the total number of bytes remaining in the specified444* subsequence of the given buffer array, that is,445*446* <blockquote><pre>447* dsts[offset].remaining()448* + dsts[offset+1].remaining()449* + ... + dsts[offset+length-1].remaining()</pre></blockquote>450*451* at the moment that the read is attempted.452*453* <p> Suppose that a byte sequence of length <i>n</i> is read, where454* <tt>0</tt> <tt><</tt> <i>n</i> <tt><=</tt> <i>r</i>.455* Up to the first <tt>dsts[offset].remaining()</tt> bytes of this sequence456* are transferred into buffer <tt>dsts[offset]</tt>, up to the next457* <tt>dsts[offset+1].remaining()</tt> bytes are transferred into buffer458* <tt>dsts[offset+1]</tt>, and so forth, until the entire byte sequence459* is transferred into the given buffers. As many bytes as possible are460* transferred into each buffer, hence the final position of each updated461* buffer, except the last updated buffer, is guaranteed to be equal to462* that buffer's limit. The underlying operating system may impose a limit463* on the number of buffers that may be used in an I/O operation. Where the464* number of buffers (with bytes remaining), exceeds this limit, then the465* I/O operation is performed with the maximum number of buffers allowed by466* the operating system.467*468* <p> If a timeout is specified and the timeout elapses before the operation469* completes then it completes with the exception {@link470* InterruptedByTimeoutException}. Where a timeout occurs, and the471* implementation cannot guarantee that bytes have not been read, or will not472* be read from the channel into the given buffers, then further attempts to473* read from the channel will cause an unspecific runtime exception to be474* thrown.475*476* @param <A>477* The type of the attachment478* @param dsts479* The buffers into which bytes are to be transferred480* @param offset481* The offset within the buffer array of the first buffer into which482* bytes are to be transferred; must be non-negative and no larger than483* {@code dsts.length}484* @param length485* The maximum number of buffers to be accessed; must be non-negative486* and no larger than {@code dsts.length - offset}487* @param timeout488* The maximum time for the I/O operation to complete489* @param unit490* The time unit of the {@code timeout} argument491* @param attachment492* The object to attach to the I/O operation; can be {@code null}493* @param handler494* The handler for consuming the result495*496* @throws IndexOutOfBoundsException497* If the pre-conditions for the {@code offset} and {@code length}498* parameter aren't met499* @throws IllegalArgumentException500* If the buffer is read-only501* @throws ReadPendingException502* If a read operation is already in progress on this channel503* @throws NotYetConnectedException504* If this channel is not yet connected505* @throws ShutdownChannelGroupException506* If the channel group has terminated507*/508public abstract <A> void read(ByteBuffer[] dsts,509int offset,510int length,511long timeout,512TimeUnit unit,513A attachment,514CompletionHandler<Long,? super A> handler);515516/**517* Writes a sequence of bytes to this channel from the given buffer.518*519* <p> This method initiates an asynchronous write operation to write a520* sequence of bytes to this channel from the given buffer. The {@code521* handler} parameter is a completion handler that is invoked when the write522* operation completes (or fails). The result passed to the completion523* handler is the number of bytes written.524*525* <p> If a timeout is specified and the timeout elapses before the operation526* completes then it completes with the exception {@link527* InterruptedByTimeoutException}. Where a timeout occurs, and the528* implementation cannot guarantee that bytes have not been written, or will529* not be written to the channel from the given buffer, then further attempts530* to write to the channel will cause an unspecific runtime exception to be531* thrown.532*533* <p> Otherwise this method works in the same manner as the {@link534* AsynchronousByteChannel#write(ByteBuffer,Object,CompletionHandler)}535* method.536*537* @param <A>538* The type of the attachment539* @param src540* The buffer from which bytes are to be retrieved541* @param timeout542* The maximum time for the I/O operation to complete543* @param unit544* The time unit of the {@code timeout} argument545* @param attachment546* The object to attach to the I/O operation; can be {@code null}547* @param handler548* The handler for consuming the result549*550* @throws WritePendingException551* If a write operation is already in progress on this channel552* @throws NotYetConnectedException553* If this channel is not yet connected554* @throws ShutdownChannelGroupException555* If the channel group has terminated556*/557public abstract <A> void write(ByteBuffer src,558long timeout,559TimeUnit unit,560A attachment,561CompletionHandler<Integer,? super A> handler);562563/**564* @throws WritePendingException {@inheritDoc}565* @throws NotYetConnectedException566* If this channel is not yet connected567* @throws ShutdownChannelGroupException568* If the channel group has terminated569*/570@Override571public final <A> void write(ByteBuffer src,572A attachment,573CompletionHandler<Integer,? super A> handler)574575{576write(src, 0L, TimeUnit.MILLISECONDS, attachment, handler);577}578579/**580* @throws WritePendingException {@inheritDoc}581* @throws NotYetConnectedException582* If this channel is not yet connected583*/584@Override585public abstract Future<Integer> write(ByteBuffer src);586587/**588* Writes a sequence of bytes to this channel from a subsequence of the given589* buffers. This operation, sometimes called a <em>gathering write</em>, is590* often useful when implementing network protocols that group data into591* segments consisting of one or more fixed-length headers followed by a592* variable-length body. The {@code handler} parameter is a completion593* handler that is invoked when the write operation completes (or fails).594* The result passed to the completion handler is the number of bytes written.595*596* <p> This method initiates a write of up to <i>r</i> bytes to this channel,597* where <i>r</i> is the total number of bytes remaining in the specified598* subsequence of the given buffer array, that is,599*600* <blockquote><pre>601* srcs[offset].remaining()602* + srcs[offset+1].remaining()603* + ... + srcs[offset+length-1].remaining()</pre></blockquote>604*605* at the moment that the write is attempted.606*607* <p> Suppose that a byte sequence of length <i>n</i> is written, where608* <tt>0</tt> <tt><</tt> <i>n</i> <tt><=</tt> <i>r</i>.609* Up to the first <tt>srcs[offset].remaining()</tt> bytes of this sequence610* are written from buffer <tt>srcs[offset]</tt>, up to the next611* <tt>srcs[offset+1].remaining()</tt> bytes are written from buffer612* <tt>srcs[offset+1]</tt>, and so forth, until the entire byte sequence is613* written. As many bytes as possible are written from each buffer, hence614* the final position of each updated buffer, except the last updated615* buffer, is guaranteed to be equal to that buffer's limit. The underlying616* operating system may impose a limit on the number of buffers that may be617* used in an I/O operation. Where the number of buffers (with bytes618* remaining), exceeds this limit, then the I/O operation is performed with619* the maximum number of buffers allowed by the operating system.620*621* <p> If a timeout is specified and the timeout elapses before the operation622* completes then it completes with the exception {@link623* InterruptedByTimeoutException}. Where a timeout occurs, and the624* implementation cannot guarantee that bytes have not been written, or will625* not be written to the channel from the given buffers, then further attempts626* to write to the channel will cause an unspecific runtime exception to be627* thrown.628*629* @param <A>630* The type of the attachment631* @param srcs632* The buffers from which bytes are to be retrieved633* @param offset634* The offset within the buffer array of the first buffer from which635* bytes are to be retrieved; must be non-negative and no larger636* than {@code srcs.length}637* @param length638* The maximum number of buffers to be accessed; must be non-negative639* and no larger than {@code srcs.length - offset}640* @param timeout641* The maximum time for the I/O operation to complete642* @param unit643* The time unit of the {@code timeout} argument644* @param attachment645* The object to attach to the I/O operation; can be {@code null}646* @param handler647* The handler for consuming the result648*649* @throws IndexOutOfBoundsException650* If the pre-conditions for the {@code offset} and {@code length}651* parameter aren't met652* @throws WritePendingException653* If a write operation is already in progress on this channel654* @throws NotYetConnectedException655* If this channel is not yet connected656* @throws ShutdownChannelGroupException657* If the channel group has terminated658*/659public abstract <A> void write(ByteBuffer[] srcs,660int offset,661int length,662long timeout,663TimeUnit unit,664A attachment,665CompletionHandler<Long,? super A> handler);666667/**668* {@inheritDoc}669* <p>670* If there is a security manager set, its {@code checkConnect} method is671* called with the local address and {@code -1} as its arguments to see672* if the operation is allowed. If the operation is not allowed,673* a {@code SocketAddress} representing the674* {@link java.net.InetAddress#getLoopbackAddress loopback} address and the675* local port of the channel's socket is returned.676*677* @return The {@code SocketAddress} that the socket is bound to, or the678* {@code SocketAddress} representing the loopback address if679* denied by the security manager, or {@code null} if the680* channel's socket is not bound681*682* @throws ClosedChannelException {@inheritDoc}683* @throws IOException {@inheritDoc}684*/685public abstract SocketAddress getLocalAddress() throws IOException;686}687688689