Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/src/share/classes/java/nio/channels/SocketChannel.java
38918 views
/*1* Copyright (c) 2000, 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.io.IOException;28import java.net.Socket;29import java.net.SocketOption;30import java.net.SocketAddress;31import java.nio.ByteBuffer;32import java.nio.channels.spi.AbstractSelectableChannel;33import java.nio.channels.spi.SelectorProvider;3435/**36* A selectable channel for stream-oriented connecting sockets.37*38* <p> A socket channel is created by invoking one of the {@link #open open}39* methods of this class. It is not possible to create a channel for an arbitrary,40* pre-existing socket. A newly-created socket channel is open but not yet41* connected. An attempt to invoke an I/O operation upon an unconnected42* channel will cause a {@link NotYetConnectedException} to be thrown. A43* socket channel can be connected by invoking its {@link #connect connect}44* method; once connected, a socket channel remains connected until it is45* closed. Whether or not a socket channel is connected may be determined by46* invoking its {@link #isConnected isConnected} method.47*48* <p> Socket channels support <i>non-blocking connection:</i> A socket49* channel may be created and the process of establishing the link to the50* remote socket may be initiated via the {@link #connect connect} method for51* later completion by the {@link #finishConnect finishConnect} method.52* Whether or not a connection operation is in progress may be determined by53* invoking the {@link #isConnectionPending isConnectionPending} method.54*55* <p> Socket channels support <i>asynchronous shutdown,</i> which is similar56* to the asynchronous close operation specified in the {@link Channel} class.57* If the input side of a socket is shut down by one thread while another58* thread is blocked in a read operation on the socket's channel, then the read59* operation in the blocked thread will complete without reading any bytes and60* will return <tt>-1</tt>. If the output side of a socket is shut down by one61* thread while another thread is blocked in a write operation on the socket's62* channel, then the blocked thread will receive an {@link63* AsynchronousCloseException}.64*65* <p> Socket options are configured using the {@link #setOption(SocketOption,Object)66* setOption} method. Socket channels support the following options:67* <blockquote>68* <table border summary="Socket options">69* <tr>70* <th>Option Name</th>71* <th>Description</th>72* </tr>73* <tr>74* <td> {@link java.net.StandardSocketOptions#SO_SNDBUF SO_SNDBUF} </td>75* <td> The size of the socket send buffer </td>76* </tr>77* <tr>78* <td> {@link java.net.StandardSocketOptions#SO_RCVBUF SO_RCVBUF} </td>79* <td> The size of the socket receive buffer </td>80* </tr>81* <tr>82* <td> {@link java.net.StandardSocketOptions#SO_KEEPALIVE SO_KEEPALIVE} </td>83* <td> Keep connection alive </td>84* </tr>85* <tr>86* <td> {@link java.net.StandardSocketOptions#SO_REUSEADDR SO_REUSEADDR} </td>87* <td> Re-use address </td>88* </tr>89* <tr>90* <td> {@link java.net.StandardSocketOptions#SO_LINGER SO_LINGER} </td>91* <td> Linger on close if data is present (when configured in blocking mode92* only) </td>93* </tr>94* <tr>95* <td> {@link java.net.StandardSocketOptions#TCP_NODELAY TCP_NODELAY} </td>96* <td> Disable the Nagle algorithm </td>97* </tr>98* </table>99* </blockquote>100* Additional (implementation specific) options may also be supported.101*102* <p> Socket channels are safe for use by multiple concurrent threads. They103* support concurrent reading and writing, though at most one thread may be104* reading and at most one thread may be writing at any given time. The {@link105* #connect connect} and {@link #finishConnect finishConnect} methods are106* mutually synchronized against each other, and an attempt to initiate a read107* or write operation while an invocation of one of these methods is in108* progress will block until that invocation is complete. </p>109*110* @author Mark Reinhold111* @author JSR-51 Expert Group112* @since 1.4113*/114115public abstract class SocketChannel116extends AbstractSelectableChannel117implements ByteChannel, ScatteringByteChannel, GatheringByteChannel, NetworkChannel118{119120/**121* Initializes a new instance of this class.122*123* @param provider124* The provider that created this channel125*/126protected SocketChannel(SelectorProvider provider) {127super(provider);128}129130/**131* Opens a socket channel.132*133* <p> The new channel is created by invoking the {@link134* java.nio.channels.spi.SelectorProvider#openSocketChannel135* openSocketChannel} method of the system-wide default {@link136* java.nio.channels.spi.SelectorProvider} object. </p>137*138* @return A new socket channel139*140* @throws IOException141* If an I/O error occurs142*/143public static SocketChannel open() throws IOException {144return SelectorProvider.provider().openSocketChannel();145}146147/**148* Opens a socket channel and connects it to a remote address.149*150* <p> This convenience method works as if by invoking the {@link #open()}151* method, invoking the {@link #connect(SocketAddress) connect} method upon152* the resulting socket channel, passing it <tt>remote</tt>, and then153* returning that channel. </p>154*155* @param remote156* The remote address to which the new channel is to be connected157*158* @return A new, and connected, socket channel159*160* @throws AsynchronousCloseException161* If another thread closes this channel162* while the connect operation is in progress163*164* @throws ClosedByInterruptException165* If another thread interrupts the current thread166* while the connect operation is in progress, thereby167* closing the channel and setting the current thread's168* interrupt status169*170* @throws UnresolvedAddressException171* If the given remote address is not fully resolved172*173* @throws UnsupportedAddressTypeException174* If the type of the given remote address is not supported175*176* @throws SecurityException177* If a security manager has been installed178* and it does not permit access to the given remote endpoint179*180* @throws IOException181* If some other I/O error occurs182*/183public static SocketChannel open(SocketAddress remote)184throws IOException185{186SocketChannel sc = open();187try {188sc.connect(remote);189} catch (Throwable x) {190try {191sc.close();192} catch (Throwable suppressed) {193x.addSuppressed(suppressed);194}195throw x;196}197assert sc.isConnected();198return sc;199}200201/**202* Returns an operation set identifying this channel's supported203* operations.204*205* <p> Socket channels support connecting, reading, and writing, so this206* method returns <tt>(</tt>{@link SelectionKey#OP_CONNECT}207* <tt>|</tt> {@link SelectionKey#OP_READ} <tt>|</tt> {@link208* SelectionKey#OP_WRITE}<tt>)</tt>. </p>209*210* @return The valid-operation set211*/212public final int validOps() {213return (SelectionKey.OP_READ214| SelectionKey.OP_WRITE215| SelectionKey.OP_CONNECT);216}217218219// -- Socket-specific operations --220221/**222* @throws ConnectionPendingException223* If a non-blocking connect operation is already in progress on224* this channel225* @throws AlreadyBoundException {@inheritDoc}226* @throws UnsupportedAddressTypeException {@inheritDoc}227* @throws ClosedChannelException {@inheritDoc}228* @throws IOException {@inheritDoc}229* @throws SecurityException230* If a security manager has been installed and its231* {@link SecurityManager#checkListen checkListen} method denies232* the operation233*234* @since 1.7235*/236@Override237public abstract SocketChannel bind(SocketAddress local)238throws IOException;239240/**241* @throws UnsupportedOperationException {@inheritDoc}242* @throws IllegalArgumentException {@inheritDoc}243* @throws ClosedChannelException {@inheritDoc}244* @throws IOException {@inheritDoc}245*246* @since 1.7247*/248@Override249public abstract <T> SocketChannel setOption(SocketOption<T> name, T value)250throws IOException;251252/**253* Shutdown the connection for reading without closing the channel.254*255* <p> Once shutdown for reading then further reads on the channel will256* return {@code -1}, the end-of-stream indication. If the input side of the257* connection is already shutdown then invoking this method has no effect.258*259* @return The channel260*261* @throws NotYetConnectedException262* If this channel is not yet connected263* @throws ClosedChannelException264* If this channel is closed265* @throws IOException266* If some other I/O error occurs267*268* @since 1.7269*/270public abstract SocketChannel shutdownInput() throws IOException;271272/**273* Shutdown the connection for writing without closing the channel.274*275* <p> Once shutdown for writing then further attempts to write to the276* channel will throw {@link ClosedChannelException}. If the output side of277* the connection is already shutdown then invoking this method has no278* effect.279*280* @return The channel281*282* @throws NotYetConnectedException283* If this channel is not yet connected284* @throws ClosedChannelException285* If this channel is closed286* @throws IOException287* If some other I/O error occurs288*289* @since 1.7290*/291public abstract SocketChannel shutdownOutput() throws IOException;292293/**294* Retrieves a socket associated with this channel.295*296* <p> The returned object will not declare any public methods that are not297* declared in the {@link java.net.Socket} class. </p>298*299* @return A socket associated with this channel300*/301public abstract Socket socket();302303/**304* Tells whether or not this channel's network socket is connected.305*306* @return <tt>true</tt> if, and only if, this channel's network socket307* is {@link #isOpen open} and connected308*/309public abstract boolean isConnected();310311/**312* Tells whether or not a connection operation is in progress on this313* channel.314*315* @return <tt>true</tt> if, and only if, a connection operation has been316* initiated on this channel but not yet completed by invoking the317* {@link #finishConnect finishConnect} method318*/319public abstract boolean isConnectionPending();320321/**322* Connects this channel's socket.323*324* <p> If this channel is in non-blocking mode then an invocation of this325* method initiates a non-blocking connection operation. If the connection326* is established immediately, as can happen with a local connection, then327* this method returns <tt>true</tt>. Otherwise this method returns328* <tt>false</tt> and the connection operation must later be completed by329* invoking the {@link #finishConnect finishConnect} method.330*331* <p> If this channel is in blocking mode then an invocation of this332* method will block until the connection is established or an I/O error333* occurs.334*335* <p> This method performs exactly the same security checks as the {@link336* java.net.Socket} class. That is, if a security manager has been337* installed then this method verifies that its {@link338* java.lang.SecurityManager#checkConnect checkConnect} method permits339* connecting to the address and port number of the given remote endpoint.340*341* <p> This method may be invoked at any time. If a read or write342* operation upon this channel is invoked while an invocation of this343* method is in progress then that operation will first block until this344* invocation is complete. If a connection attempt is initiated but fails,345* that is, if an invocation of this method throws a checked exception,346* then the channel will be closed. </p>347*348* @param remote349* The remote address to which this channel is to be connected350*351* @return <tt>true</tt> if a connection was established,352* <tt>false</tt> if this channel is in non-blocking mode353* and the connection operation is in progress354*355* @throws AlreadyConnectedException356* If this channel is already connected357*358* @throws ConnectionPendingException359* If a non-blocking connection operation is already in progress360* on this channel361*362* @throws ClosedChannelException363* If this channel is closed364*365* @throws AsynchronousCloseException366* If another thread closes this channel367* while the connect operation is in progress368*369* @throws ClosedByInterruptException370* If another thread interrupts the current thread371* while the connect operation is in progress, thereby372* closing the channel and setting the current thread's373* interrupt status374*375* @throws UnresolvedAddressException376* If the given remote address is not fully resolved377*378* @throws UnsupportedAddressTypeException379* If the type of the given remote address is not supported380*381* @throws SecurityException382* If a security manager has been installed383* and it does not permit access to the given remote endpoint384*385* @throws IOException386* If some other I/O error occurs387*/388public abstract boolean connect(SocketAddress remote) throws IOException;389390/**391* Finishes the process of connecting a socket channel.392*393* <p> A non-blocking connection operation is initiated by placing a socket394* channel in non-blocking mode and then invoking its {@link #connect395* connect} method. Once the connection is established, or the attempt has396* failed, the socket channel will become connectable and this method may397* be invoked to complete the connection sequence. If the connection398* operation failed then invoking this method will cause an appropriate399* {@link java.io.IOException} to be thrown.400*401* <p> If this channel is already connected then this method will not block402* and will immediately return <tt>true</tt>. If this channel is in403* non-blocking mode then this method will return <tt>false</tt> if the404* connection process is not yet complete. If this channel is in blocking405* mode then this method will block until the connection either completes406* or fails, and will always either return <tt>true</tt> or throw a checked407* exception describing the failure.408*409* <p> This method may be invoked at any time. If a read or write410* operation upon this channel is invoked while an invocation of this411* method is in progress then that operation will first block until this412* invocation is complete. If a connection attempt fails, that is, if an413* invocation of this method throws a checked exception, then the channel414* will be closed. </p>415*416* @return <tt>true</tt> if, and only if, this channel's socket is now417* connected418*419* @throws NoConnectionPendingException420* If this channel is not connected and a connection operation421* has not been initiated422*423* @throws ClosedChannelException424* If this channel is closed425*426* @throws AsynchronousCloseException427* If another thread closes this channel428* while the connect operation is in progress429*430* @throws ClosedByInterruptException431* If another thread interrupts the current thread432* while the connect operation is in progress, thereby433* closing the channel and setting the current thread's434* interrupt status435*436* @throws IOException437* If some other I/O error occurs438*/439public abstract boolean finishConnect() throws IOException;440441/**442* Returns the remote address to which this channel's socket is connected.443*444* <p> Where the channel is bound and connected to an Internet Protocol445* socket address then the return value from this method is of type {@link446* java.net.InetSocketAddress}.447*448* @return The remote address; {@code null} if the channel's socket is not449* connected450*451* @throws ClosedChannelException452* If the channel is closed453* @throws IOException454* If an I/O error occurs455*456* @since 1.7457*/458public abstract SocketAddress getRemoteAddress() throws IOException;459460// -- ByteChannel operations --461462/**463* @throws NotYetConnectedException464* If this channel is not yet connected465*/466public abstract int read(ByteBuffer dst) throws IOException;467468/**469* @throws NotYetConnectedException470* If this channel is not yet connected471*/472public abstract long read(ByteBuffer[] dsts, int offset, int length)473throws IOException;474475/**476* @throws NotYetConnectedException477* If this channel is not yet connected478*/479public final long read(ByteBuffer[] dsts) throws IOException {480return read(dsts, 0, dsts.length);481}482483/**484* @throws NotYetConnectedException485* If this channel is not yet connected486*/487public abstract int write(ByteBuffer src) throws IOException;488489/**490* @throws NotYetConnectedException491* If this channel is not yet connected492*/493public abstract long write(ByteBuffer[] srcs, int offset, int length)494throws IOException;495496/**497* @throws NotYetConnectedException498* If this channel is not yet connected499*/500public final long write(ByteBuffer[] srcs) throws IOException {501return write(srcs, 0, srcs.length);502}503504/**505* {@inheritDoc}506* <p>507* If there is a security manager set, its {@code checkConnect} method is508* called with the local address and {@code -1} as its arguments to see509* if the operation is allowed. If the operation is not allowed,510* a {@code SocketAddress} representing the511* {@link java.net.InetAddress#getLoopbackAddress loopback} address and the512* local port of the channel's socket is returned.513*514* @return The {@code SocketAddress} that the socket is bound to, or the515* {@code SocketAddress} representing the loopback address if516* denied by the security manager, or {@code null} if the517* channel's socket is not bound518*519* @throws ClosedChannelException {@inheritDoc}520* @throws IOException {@inheritDoc}521*/522@Override523public abstract SocketAddress getLocalAddress() throws IOException;524525}526527528