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