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