1 /* 2 * Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. Oracle designates this 8 * particular file as subject to the "Classpath" exception as provided 9 * by Oracle in the LICENSE file that accompanied this code. 10 * 11 * This code is distributed in the hope that it will be useful, but WITHOUT 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 * version 2 for more details (a copy is included in the LICENSE file that 15 * accompanied this code). 16 * 17 * You should have received a copy of the GNU General Public License version 18 * 2 along with this work; if not, write to the Free Software Foundation, 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 * 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 * or visit www.oracle.com if you need additional information or have any 23 * questions. 24 */ 25 26 package java.nio.channels; 27 28 import java.io.IOException; 29 import java.net.ProtocolFamily; 30 import java.net.Socket; 31 import java.net.SocketOption; 32 import java.net.SocketAddress; 33 import java.nio.ByteBuffer; 34 import java.nio.channels.spi.AbstractSelectableChannel; 35 import java.nio.channels.spi.SelectorProvider; 36 import static java.util.Objects.requireNonNull; 37 38 /** 39 * A selectable channel for stream-oriented connecting sockets. 40 * 41 * <p> A socket channel is created by invoking one of the {@link #open open} 42 * methods of this class. It is not possible to create a channel for an arbitrary, 43 * pre-existing socket. A newly-created socket channel is open but not yet 44 * connected. An attempt to invoke an I/O operation upon an unconnected 45 * channel will cause a {@link NotYetConnectedException} to be thrown. A 46 * socket channel can be connected by invoking its {@link #connect connect} 47 * method; once connected, a socket channel remains connected until it is 48 * closed. Whether or not a socket channel is connected may be determined by 49 * invoking its {@link #isConnected isConnected} method. 50 * 51 * <p> Socket channels support <i>non-blocking connection:</i> A socket 52 * channel may be created and the process of establishing the link to the 53 * remote socket may be initiated via the {@link #connect connect} method for 54 * later completion by the {@link #finishConnect finishConnect} method. 55 * Whether or not a connection operation is in progress may be determined by 56 * invoking the {@link #isConnectionPending isConnectionPending} method. 57 * 58 * <p> Socket channels support <i>asynchronous shutdown,</i> which is similar 59 * to the asynchronous close operation specified in the {@link Channel} class. 60 * If the input side of a socket is shut down by one thread while another 61 * thread is blocked in a read operation on the socket's channel, then the read 62 * operation in the blocked thread will complete without reading any bytes and 63 * will return {@code -1}. If the output side of a socket is shut down by one 64 * thread while another thread is blocked in a write operation on the socket's 65 * channel, then the blocked thread will receive an {@link 66 * AsynchronousCloseException}. 67 * 68 * <p> Socket options are configured using the {@link #setOption(SocketOption,Object) 69 * setOption} method. Socket channels support the following options: 70 * <blockquote> 71 * <table class="striped"> 72 * <caption style="display:none">Socket options</caption> 73 * <thead> 74 * <tr> 75 * <th scope="col">Option Name</th> 76 * <th scope="col">Description</th> 77 * </tr> 78 * </thead> 79 * <tbody> 80 * <tr> 81 * <th scope="row"> {@link java.net.StandardSocketOptions#SO_SNDBUF SO_SNDBUF} </th> 82 * <td> The size of the socket send buffer </td> 83 * </tr> 84 * <tr> 85 * <th scope="row"> {@link java.net.StandardSocketOptions#SO_RCVBUF SO_RCVBUF} </th> 86 * <td> The size of the socket receive buffer </td> 87 * </tr> 88 * <tr> 89 * <th scope="row"> {@link java.net.StandardSocketOptions#SO_KEEPALIVE SO_KEEPALIVE} </th> 90 * <td> Keep connection alive </td> 91 * </tr> 92 * <tr> 93 * <th scope="row"> {@link java.net.StandardSocketOptions#SO_REUSEADDR SO_REUSEADDR} </th> 94 * <td> Re-use address </td> 95 * </tr> 96 * <tr> 97 * <th scope="row"> {@link java.net.StandardSocketOptions#SO_LINGER SO_LINGER} </th> 98 * <td> Linger on close if data is present (when configured in blocking mode 99 * only) </td> 100 * </tr> 101 * <tr> 102 * <th scope="row"> {@link java.net.StandardSocketOptions#TCP_NODELAY TCP_NODELAY} </th> 103 * <td> Disable the Nagle algorithm </td> 104 * </tr> 105 * </tbody> 106 * </table> 107 * </blockquote> 108 * Additional (implementation specific) options may also be supported. 109 * 110 * <p> Socket channels are safe for use by multiple concurrent threads. They 111 * support concurrent reading and writing, though at most one thread may be 112 * reading and at most one thread may be writing at any given time. The {@link 113 * #connect connect} and {@link #finishConnect finishConnect} methods are 114 * mutually synchronized against each other, and an attempt to initiate a read 115 * or write operation while an invocation of one of these methods is in 116 * progress will block until that invocation is complete. </p> 117 * 118 * @author Mark Reinhold 119 * @author JSR-51 Expert Group 120 * @since 1.4 121 */ 122 123 public abstract class SocketChannel 124 extends AbstractSelectableChannel 125 implements ByteChannel, ScatteringByteChannel, GatheringByteChannel, NetworkChannel 126 { 127 128 /** 129 * Initializes a new instance of this class. 130 * 131 * @param provider 132 * The provider that created this channel 133 */ 134 protected SocketChannel(SelectorProvider provider) { 135 super(provider); 136 } 137 138 /** 139 * Opens a socket channel. 140 * 141 * <p> The new channel is created by invoking the {@link 142 * java.nio.channels.spi.SelectorProvider#openSocketChannel 143 * openSocketChannel} method of the system-wide default {@link 144 * java.nio.channels.spi.SelectorProvider} object. </p> 145 * 146 * @return A new socket channel 147 * 148 * @throws IOException 149 * If an I/O error occurs 150 */ 151 public static SocketChannel open() throws IOException { 152 return SelectorProvider.provider().openSocketChannel(); 153 } 154 155 /** 156 * Opens a socket channel. The {@code family} parameter specifies the 157 * {@link ProtocolFamily protocol family} of the channel's socket. 158 * 159 * <p> The new channel is created by invoking the {@link 160 * java.nio.channels.spi.SelectorProvider#openSocketChannel(ProtocolFamily) 161 * openSocketChannel(ProtocolFamily)} method of the system-wide default. 162 * {@link java.nio.channels.spi.SelectorProvider} object.</p> 163 * 164 * @param family 165 * The protocol family 166 * 167 * @return A new socket channel 168 * 169 * @throws UnsupportedOperationException 170 * If the specified protocol family is not supported. For example, 171 * suppose the parameter is specified as {@link 172 * java.net.StandardProtocolFamily#INET6 StandardProtocolFamily.INET6} 173 * but IPv6 is not enabled on the platform. 174 * @throws IOException 175 * If an I/O error occurs 176 * 177 * @since 15 178 */ 179 public static SocketChannel open(ProtocolFamily family) throws IOException { 180 return SelectorProvider.provider().openSocketChannel(requireNonNull(family)); 181 } 182 183 /** 184 * Opens a socket channel and connects it to a remote address. 185 * 186 * <p> This convenience method works as if by invoking the {@link #open()} 187 * method, invoking the {@link #connect(SocketAddress) connect} method upon 188 * the resulting socket channel, passing it {@code remote}, and then 189 * returning that channel. </p> 190 * 191 * @param remote 192 * The remote address to which the new channel is to be connected 193 * 194 * @return A new, and connected, socket channel 195 * 196 * @throws AsynchronousCloseException 197 * If another thread closes this channel 198 * while the connect operation is in progress 199 * 200 * @throws ClosedByInterruptException 201 * If another thread interrupts the current thread 202 * while the connect operation is in progress, thereby 203 * closing the channel and setting the current thread's 204 * interrupt status 205 * 206 * @throws UnresolvedAddressException 207 * If the given remote address is not fully resolved 208 * 209 * @throws UnsupportedAddressTypeException 210 * If the type of the given remote address is not supported 211 * 212 * @throws SecurityException 213 * If a security manager has been installed 214 * and it does not permit access to the given remote endpoint 215 * 216 * @throws IOException 217 * If some other I/O error occurs 218 */ 219 public static SocketChannel open(SocketAddress remote) 220 throws IOException 221 { 222 SocketChannel sc = open(); 223 try { 224 sc.connect(remote); 225 } catch (Throwable x) { 226 try { 227 sc.close(); 228 } catch (Throwable suppressed) { 229 x.addSuppressed(suppressed); 230 } 231 throw x; 232 } 233 assert sc.isConnected(); 234 return sc; 235 } 236 237 /** 238 * Returns an operation set identifying this channel's supported 239 * operations. 240 * 241 * <p> Socket channels support connecting, reading, and writing, so this 242 * method returns {@code (}{@link SelectionKey#OP_CONNECT} 243 * {@code |} {@link SelectionKey#OP_READ} {@code |} {@link 244 * SelectionKey#OP_WRITE}{@code )}. 245 * 246 * @return The valid-operation set 247 */ 248 public final int validOps() { 249 return (SelectionKey.OP_READ 250 | SelectionKey.OP_WRITE 251 | SelectionKey.OP_CONNECT); 252 } 253 254 255 // -- Socket-specific operations -- 256 257 /** 258 * @throws ConnectionPendingException 259 * If a non-blocking connect operation is already in progress on 260 * this channel 261 * @throws AlreadyBoundException {@inheritDoc} 262 * @throws UnsupportedAddressTypeException {@inheritDoc} 263 * @throws ClosedChannelException {@inheritDoc} 264 * @throws IOException {@inheritDoc} 265 * @throws SecurityException 266 * If a security manager has been installed and its 267 * {@link SecurityManager#checkListen checkListen} method denies 268 * the operation 269 * 270 * @since 1.7 271 */ 272 @Override 273 public abstract SocketChannel bind(SocketAddress local) 274 throws IOException; 275 276 /** 277 * @throws UnsupportedOperationException {@inheritDoc} 278 * @throws IllegalArgumentException {@inheritDoc} 279 * @throws ClosedChannelException {@inheritDoc} 280 * @throws IOException {@inheritDoc} 281 * 282 * @since 1.7 283 */ 284 @Override 285 public abstract <T> SocketChannel setOption(SocketOption<T> name, T value) 286 throws IOException; 287 288 /** 289 * Shutdown the connection for reading without closing the channel. 290 * 291 * <p> Once shutdown for reading then further reads on the channel will 292 * return {@code -1}, the end-of-stream indication. If the input side of the 293 * connection is already shutdown then invoking this method has no effect. 294 * 295 * @return The channel 296 * 297 * @throws NotYetConnectedException 298 * If this channel is not yet connected 299 * @throws ClosedChannelException 300 * If this channel is closed 301 * @throws IOException 302 * If some other I/O error occurs 303 * 304 * @since 1.7 305 */ 306 public abstract SocketChannel shutdownInput() throws IOException; 307 308 /** 309 * Shutdown the connection for writing without closing the channel. 310 * 311 * <p> Once shutdown for writing then further attempts to write to the 312 * channel will throw {@link ClosedChannelException}. If the output side of 313 * the connection is already shutdown then invoking this method has no 314 * effect. 315 * 316 * @return The channel 317 * 318 * @throws NotYetConnectedException 319 * If this channel is not yet connected 320 * @throws ClosedChannelException 321 * If this channel is closed 322 * @throws IOException 323 * If some other I/O error occurs 324 * 325 * @since 1.7 326 */ 327 public abstract SocketChannel shutdownOutput() throws IOException; 328 329 /** 330 * Retrieves a socket associated with this channel. 331 * 332 * <p> The returned object will not declare any public methods that are not 333 * declared in the {@link java.net.Socket} class. </p> 334 * 335 * @return A socket associated with this channel 336 */ 337 public abstract Socket socket(); 338 339 /** 340 * Tells whether or not this channel's network socket is connected. 341 * 342 * @return {@code true} if, and only if, this channel's network socket 343 * is {@link #isOpen open} and connected 344 */ 345 public abstract boolean isConnected(); 346 347 /** 348 * Tells whether or not a connection operation is in progress on this 349 * channel. 350 * 351 * @return {@code true} if, and only if, a connection operation has been 352 * initiated on this channel but not yet completed by invoking the 353 * {@link #finishConnect finishConnect} method 354 */ 355 public abstract boolean isConnectionPending(); 356 357 /** 358 * Connects this channel's socket. 359 * 360 * <p> If this channel is in non-blocking mode then an invocation of this 361 * method initiates a non-blocking connection operation. If the connection 362 * is established immediately, as can happen with a local connection, then 363 * this method returns {@code true}. Otherwise this method returns 364 * {@code false} and the connection operation must later be completed by 365 * invoking the {@link #finishConnect finishConnect} method. 366 * 367 * <p> If this channel is in blocking mode then an invocation of this 368 * method will block until the connection is established or an I/O error 369 * occurs. 370 * 371 * <p> This method performs exactly the same security checks as the {@link 372 * java.net.Socket} class. That is, if a security manager has been 373 * installed then this method verifies that its {@link 374 * java.lang.SecurityManager#checkConnect checkConnect} method permits 375 * connecting to the address and port number of the given remote endpoint. 376 * 377 * <p> This method may be invoked at any time. If a read or write 378 * operation upon this channel is invoked while an invocation of this 379 * method is in progress then that operation will first block until this 380 * invocation is complete. If a connection attempt is initiated but fails, 381 * that is, if an invocation of this method throws a checked exception, 382 * then the channel will be closed. </p> 383 * 384 * @param remote 385 * The remote address to which this channel is to be connected 386 * 387 * @return {@code true} if a connection was established, 388 * {@code false} if this channel is in non-blocking mode 389 * and the connection operation is in progress 390 * 391 * @throws AlreadyConnectedException 392 * If this channel is already connected 393 * 394 * @throws ConnectionPendingException 395 * If a non-blocking connection operation is already in progress 396 * on this channel 397 * 398 * @throws ClosedChannelException 399 * If this channel is closed 400 * 401 * @throws AsynchronousCloseException 402 * If another thread closes this channel 403 * while the connect operation is in progress 404 * 405 * @throws ClosedByInterruptException 406 * If another thread interrupts the current thread 407 * while the connect operation is in progress, thereby 408 * closing the channel and setting the current thread's 409 * interrupt status 410 * 411 * @throws UnresolvedAddressException 412 * If the given remote address is not fully resolved 413 * 414 * @throws UnsupportedAddressTypeException 415 * If the type of the given remote address is not supported 416 * 417 * @throws SecurityException 418 * If a security manager has been installed 419 * and it does not permit access to the given remote endpoint 420 * 421 * @throws IOException 422 * If some other I/O error occurs 423 */ 424 public abstract boolean connect(SocketAddress remote) throws IOException; 425 426 /** 427 * Finishes the process of connecting a socket channel. 428 * 429 * <p> A non-blocking connection operation is initiated by placing a socket 430 * channel in non-blocking mode and then invoking its {@link #connect 431 * connect} method. Once the connection is established, or the attempt has 432 * failed, the socket channel will become connectable and this method may 433 * be invoked to complete the connection sequence. If the connection 434 * operation failed then invoking this method will cause an appropriate 435 * {@link java.io.IOException} to be thrown. 436 * 437 * <p> If this channel is already connected then this method will not block 438 * and will immediately return {@code true}. If this channel is in 439 * non-blocking mode then this method will return {@code false} if the 440 * connection process is not yet complete. If this channel is in blocking 441 * mode then this method will block until the connection either completes 442 * or fails, and will always either return {@code true} or throw a checked 443 * exception describing the failure. 444 * 445 * <p> This method may be invoked at any time. If a read or write 446 * operation upon this channel is invoked while an invocation of this 447 * method is in progress then that operation will first block until this 448 * invocation is complete. If a connection attempt fails, that is, if an 449 * invocation of this method throws a checked exception, then the channel 450 * will be closed. </p> 451 * 452 * @return {@code true} if, and only if, this channel's socket is now 453 * connected 454 * 455 * @throws NoConnectionPendingException 456 * If this channel is not connected and a connection operation 457 * has not been initiated 458 * 459 * @throws ClosedChannelException 460 * If this channel is closed 461 * 462 * @throws AsynchronousCloseException 463 * If another thread closes this channel 464 * while the connect operation is in progress 465 * 466 * @throws ClosedByInterruptException 467 * If another thread interrupts the current thread 468 * while the connect operation is in progress, thereby 469 * closing the channel and setting the current thread's 470 * interrupt status 471 * 472 * @throws IOException 473 * If some other I/O error occurs 474 */ 475 public abstract boolean finishConnect() throws IOException; 476 477 /** 478 * Returns the remote address to which this channel's socket is connected. 479 * 480 * <p> Where the channel is bound and connected to an Internet Protocol 481 * socket address then the return value from this method is of type {@link 482 * java.net.InetSocketAddress}. 483 * 484 * @return The remote address; {@code null} if the channel's socket is not 485 * connected 486 * 487 * @throws ClosedChannelException 488 * If the channel is closed 489 * @throws IOException 490 * If an I/O error occurs 491 * 492 * @since 1.7 493 */ 494 public abstract SocketAddress getRemoteAddress() throws IOException; 495 496 // -- ByteChannel operations -- 497 498 /** 499 * @throws NotYetConnectedException 500 * If this channel is not yet connected 501 */ 502 public abstract int read(ByteBuffer dst) throws IOException; 503 504 /** 505 * @throws NotYetConnectedException 506 * If this channel is not yet connected 507 */ 508 public abstract long read(ByteBuffer[] dsts, int offset, int length) 509 throws IOException; 510 511 /** 512 * @throws NotYetConnectedException 513 * If this channel is not yet connected 514 */ 515 public final long read(ByteBuffer[] dsts) throws IOException { 516 return read(dsts, 0, dsts.length); 517 } 518 519 /** 520 * @throws NotYetConnectedException 521 * If this channel is not yet connected 522 */ 523 public abstract int write(ByteBuffer src) throws IOException; 524 525 /** 526 * @throws NotYetConnectedException 527 * If this channel is not yet connected 528 */ 529 public abstract long write(ByteBuffer[] srcs, int offset, int length) 530 throws IOException; 531 532 /** 533 * @throws NotYetConnectedException 534 * If this channel is not yet connected 535 */ 536 public final long write(ByteBuffer[] srcs) throws IOException { 537 return write(srcs, 0, srcs.length); 538 } 539 540 /** 541 * {@inheritDoc} 542 * <p> 543 * If there is a security manager set, its {@code checkConnect} method is 544 * called with the local address and {@code -1} as its arguments to see 545 * if the operation is allowed. If the operation is not allowed, 546 * a {@code SocketAddress} representing the 547 * {@link java.net.InetAddress#getLoopbackAddress loopback} address and the 548 * local port of the channel's socket is returned. 549 * 550 * @return The {@code SocketAddress} that the socket is bound to, or the 551 * {@code SocketAddress} representing the loopback address if 552 * denied by the security manager, or {@code null} if the 553 * channel's socket is not bound 554 * 555 * @throws ClosedChannelException {@inheritDoc} 556 * @throws IOException {@inheritDoc} 557 */ 558 @Override 559 public abstract SocketAddress getLocalAddress() throws IOException; 560 561 }