1 /* 2 * Copyright (c) 2000, 2013, 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.DatagramSocket; 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 37 /** 38 * A selectable channel for datagram-oriented sockets. 39 * 40 * <p> A datagram channel is created by invoking one of the {@link #open open} methods 41 * of this class. It is not possible to create a channel for an arbitrary, 42 * pre-existing datagram socket. A newly-created datagram channel is open but not 43 * connected. A datagram channel need not be connected in order for the {@link #send 44 * send} and {@link #receive receive} methods to be used. A datagram channel may be 45 * connected, by invoking its {@link #connect connect} method, in order to 46 * avoid the overhead of the security checks are otherwise performed as part of 47 * every send and receive operation. A datagram channel must be connected in 48 * order to use the {@link #read(java.nio.ByteBuffer) read} and {@link 49 * #write(java.nio.ByteBuffer) write} methods, since those methods do not 50 * accept or return socket addresses. 51 * 52 * <p> Once connected, a datagram channel remains connected until it is 53 * disconnected or closed. Whether or not a datagram channel is connected may 54 * be determined by invoking its {@link #isConnected isConnected} method. 55 * 56 * <p> Socket options are configured using the {@link #setOption(SocketOption,Object) 57 * setOption} method. A datagram channel to an Internet Protocol socket supports 58 * the following options: 59 * <blockquote> 60 * <table border summary="Socket options"> 61 * <tr> 62 * <th>Option Name</th> 63 * <th>Description</th> 64 * </tr> 65 * <tr> 66 * <td> {@link java.net.StandardSocketOptions#SO_SNDBUF SO_SNDBUF} </td> 67 * <td> The size of the socket send buffer </td> 68 * </tr> 69 * <tr> 70 * <td> {@link java.net.StandardSocketOptions#SO_RCVBUF SO_RCVBUF} </td> 71 * <td> The size of the socket receive buffer </td> 72 * </tr> 73 * <tr> 74 * <td> {@link java.net.StandardSocketOptions#SO_REUSEADDR SO_REUSEADDR} </td> 75 * <td> Re-use address </td> 76 * </tr> 77 * <tr> 78 * <td> {@link java.net.StandardSocketOptions#SO_BROADCAST SO_BROADCAST} </td> 79 * <td> Allow transmission of broadcast datagrams </td> 80 * </tr> 81 * <tr> 82 * <td> {@link java.net.StandardSocketOptions#IP_TOS IP_TOS} </td> 83 * <td> The Type of Service (ToS) octet in the Internet Protocol (IP) header </td> 84 * </tr> 85 * <tr> 86 * <td> {@link java.net.StandardSocketOptions#IP_MULTICAST_IF IP_MULTICAST_IF} </td> 87 * <td> The network interface for Internet Protocol (IP) multicast datagrams </td> 88 * </tr> 89 * <tr> 90 * <td> {@link java.net.StandardSocketOptions#IP_MULTICAST_TTL 91 * IP_MULTICAST_TTL} </td> 92 * <td> The <em>time-to-live</em> for Internet Protocol (IP) multicast 93 * datagrams </td> 94 * </tr> 95 * <tr> 96 * <td> {@link java.net.StandardSocketOptions#IP_MULTICAST_LOOP 97 * IP_MULTICAST_LOOP} </td> 98 * <td> Loopback for Internet Protocol (IP) multicast datagrams </td> 99 * </tr> 100 * </table> 101 * </blockquote> 102 * Additional (implementation specific) options may also be supported. 103 * 104 * <p> Datagram channels are safe for use by multiple concurrent threads. They 105 * support concurrent reading and writing, though at most one thread may be 106 * reading and at most one thread may be writing at any given time. </p> 107 * 108 * @author Mark Reinhold 109 * @author JSR-51 Expert Group 110 * @since 1.4 111 */ 112 113 public abstract class DatagramChannel 114 extends AbstractSelectableChannel 115 implements ByteChannel, ScatteringByteChannel, GatheringByteChannel, MulticastChannel 116 { 117 118 /** 119 * Initializes a new instance of this class. 120 * 121 * @param provider 122 * The provider that created this channel 123 */ 124 protected DatagramChannel(SelectorProvider provider) { 125 super(provider); 126 } 127 128 /** 129 * Opens a datagram channel. 130 * 131 * <p> The new channel is created by invoking the {@link 132 * java.nio.channels.spi.SelectorProvider#openDatagramChannel() 133 * openDatagramChannel} method of the system-wide default {@link 134 * java.nio.channels.spi.SelectorProvider} object. The channel will not be 135 * connected. 136 * 137 * <p> The {@link ProtocolFamily ProtocolFamily} of the channel's socket 138 * is platform (and possibly configuration) dependent and therefore unspecified. 139 * The {@link #open(ProtocolFamily) open} allows the protocol family to be 140 * selected when opening a datagram channel, and should be used to open 141 * datagram channels that are intended for Internet Protocol multicasting. 142 * 143 * @return A new datagram channel 144 * 145 * @throws IOException 146 * If an I/O error occurs 147 */ 148 public static DatagramChannel open() throws IOException { 149 return SelectorProvider.provider().openDatagramChannel(); 150 } 151 152 /** 153 * Opens a datagram channel. 154 * 155 * <p> The {@code family} parameter is used to specify the {@link 156 * ProtocolFamily}. If the datagram channel is to be used for IP multicasting 157 * then this should correspond to the address type of the multicast groups 158 * that this channel will join. 159 * 160 * <p> The new channel is created by invoking the {@link 161 * java.nio.channels.spi.SelectorProvider#openDatagramChannel(ProtocolFamily) 162 * openDatagramChannel} method of the system-wide default {@link 163 * java.nio.channels.spi.SelectorProvider} object. The channel will not be 164 * connected. 165 * 166 * @param family 167 * The protocol family 168 * 169 * @return A new datagram channel 170 * 171 * @throws UnsupportedOperationException 172 * If the specified protocol family is not supported. For example, 173 * suppose the parameter is specified as {@link 174 * java.net.StandardProtocolFamily#INET6 StandardProtocolFamily.INET6} 175 * but IPv6 is not enabled on the platform. 176 * @throws IOException 177 * If an I/O error occurs 178 * 179 * @since 1.7 180 */ 181 public static DatagramChannel open(ProtocolFamily family) throws IOException { 182 return SelectorProvider.provider().openDatagramChannel(family); 183 } 184 185 /** 186 * Returns an operation set identifying this channel's supported 187 * operations. 188 * 189 * <p> Datagram channels support reading and writing, so this method 190 * returns <tt>(</tt>{@link SelectionKey#OP_READ} <tt>|</tt> {@link 191 * SelectionKey#OP_WRITE}<tt>)</tt>. </p> 192 * 193 * @return The valid-operation set 194 */ 195 public final int validOps() { 196 return (SelectionKey.OP_READ 197 | SelectionKey.OP_WRITE); 198 } 199 200 201 // -- Socket-specific operations -- 202 203 /** 204 * @throws AlreadyBoundException {@inheritDoc} 205 * @throws UnsupportedAddressTypeException {@inheritDoc} 206 * @throws ClosedChannelException {@inheritDoc} 207 * @throws IOException {@inheritDoc} 208 * @throws SecurityException 209 * If a security manager has been installed and its {@link 210 * SecurityManager#checkListen checkListen} method denies the 211 * operation 212 * 213 * @since 1.7 214 */ 215 public abstract DatagramChannel bind(SocketAddress local) 216 throws IOException; 217 218 /** 219 * @throws UnsupportedOperationException {@inheritDoc} 220 * @throws IllegalArgumentException {@inheritDoc} 221 * @throws ClosedChannelException {@inheritDoc} 222 * @throws IOException {@inheritDoc} 223 * 224 * @since 1.7 225 */ 226 public abstract <T> DatagramChannel setOption(SocketOption<T> name, T value) 227 throws IOException; 228 229 /** 230 * Retrieves a datagram socket associated with this channel. 231 * 232 * <p> The returned object will not declare any public methods that are not 233 * declared in the {@link java.net.DatagramSocket} class. </p> 234 * 235 * @return A datagram socket associated with this channel 236 */ 237 public abstract DatagramSocket socket(); 238 239 /** 240 * Tells whether or not this channel's socket is connected. 241 * 242 * @return {@code true} if, and only if, this channel's socket 243 * is {@link #isOpen open} and connected 244 */ 245 public abstract boolean isConnected(); 246 247 /** 248 * Connects this channel's socket. 249 * 250 * <p> The channel's socket is configured so that it only receives 251 * datagrams from, and sends datagrams to, the given remote <i>peer</i> 252 * address. Once connected, datagrams may not be received from or sent to 253 * any other address. A datagram socket remains connected until it is 254 * explicitly disconnected or until it is closed. 255 * 256 * <p> This method performs exactly the same security checks as the {@link 257 * java.net.DatagramSocket#connect connect} method of the {@link 258 * java.net.DatagramSocket} class. That is, if a security manager has been 259 * installed then this method verifies that its {@link 260 * java.lang.SecurityManager#checkAccept checkAccept} and {@link 261 * java.lang.SecurityManager#checkConnect checkConnect} methods permit 262 * datagrams to be received from and sent to, respectively, the given 263 * remote address. 264 * 265 * <p> This method may be invoked at any time. It will not have any effect 266 * on read or write operations that are already in progress at the moment 267 * that it is invoked. If this channel's socket is not bound then this method 268 * will first cause the socket to be bound to an address that is assigned 269 * automatically, as if invoking the {@link #bind bind} method with a 270 * parameter of {@code null}. </p> 271 * 272 * @param remote 273 * The remote address to which this channel is to be connected 274 * 275 * @return This datagram channel 276 * 277 * @throws ClosedChannelException 278 * If this channel is closed 279 * 280 * @throws AsynchronousCloseException 281 * If another thread closes this channel 282 * while the connect operation is in progress 283 * 284 * @throws ClosedByInterruptException 285 * If another thread interrupts the current thread 286 * while the connect operation is in progress, thereby 287 * closing the channel and setting the current thread's 288 * interrupt status 289 * 290 * @throws SecurityException 291 * If a security manager has been installed 292 * and it does not permit access to the given remote address 293 * 294 * @throws IOException 295 * If some other I/O error occurs 296 */ 297 public abstract DatagramChannel connect(SocketAddress remote) 298 throws IOException; 299 300 /** 301 * Disconnects this channel's socket. 302 * 303 * <p> The channel's socket is configured so that it can receive datagrams 304 * from, and sends datagrams to, any remote address so long as the security 305 * manager, if installed, permits it. 306 * 307 * <p> This method may be invoked at any time. It will not have any effect 308 * on read or write operations that are already in progress at the moment 309 * that it is invoked. 310 * 311 * <p> If this channel's socket is not connected, or if the channel is 312 * closed, then invoking this method has no effect. </p> 313 * 314 * @return This datagram channel 315 * 316 * @throws IOException 317 * If some other I/O error occurs 318 */ 319 public abstract DatagramChannel disconnect() throws IOException; 320 321 /** 322 * Returns the remote address to which this channel's socket is connected. 323 * 324 * @return The remote address; {@code null} if the channel's socket is not 325 * connected 326 * 327 * @throws ClosedChannelException 328 * If the channel is closed 329 * @throws IOException 330 * If an I/O error occurs 331 * 332 * @since 1.7 333 */ 334 public abstract SocketAddress getRemoteAddress() throws IOException; 335 336 /** 337 * Receives a datagram via this channel. 338 * 339 * <p> If a datagram is immediately available, or if this channel is in 340 * blocking mode and one eventually becomes available, then the datagram is 341 * copied into the given byte buffer and its source address is returned. 342 * If this channel is in non-blocking mode and a datagram is not 343 * immediately available then this method immediately returns 344 * <tt>null</tt>. 345 * 346 * <p> The datagram is transferred into the given byte buffer starting at 347 * its current position, as if by a regular {@link 348 * ReadableByteChannel#read(java.nio.ByteBuffer) read} operation. If there 349 * are fewer bytes remaining in the buffer than are required to hold the 350 * datagram then the remainder of the datagram is silently discarded. 351 * 352 * <p> This method performs exactly the same security checks as the {@link 353 * java.net.DatagramSocket#receive receive} method of the {@link 354 * java.net.DatagramSocket} class. That is, if the socket is not connected 355 * to a specific remote address and a security manager has been installed 356 * then for each datagram received this method verifies that the source's 357 * address and port number are permitted by the security manager's {@link 358 * java.lang.SecurityManager#checkAccept checkAccept} method. The overhead 359 * of this security check can be avoided by first connecting the socket via 360 * the {@link #connect connect} method. 361 * 362 * <p> This method may be invoked at any time. If another thread has 363 * already initiated a read operation upon this channel, however, then an 364 * invocation of this method will block until the first operation is 365 * complete. If this channel's socket is not bound then this method will 366 * first cause the socket to be bound to an address that is assigned 367 * automatically, as if invoking the {@link #bind bind} method with a 368 * parameter of {@code null}. </p> 369 * 370 * @param dst 371 * The buffer into which the datagram is to be transferred 372 * 373 * @return The datagram's source address, 374 * or <tt>null</tt> if this channel is in non-blocking mode 375 * and no datagram was immediately available 376 * 377 * @throws ClosedChannelException 378 * If this channel is closed 379 * 380 * @throws AsynchronousCloseException 381 * If another thread closes this channel 382 * while the read operation is in progress 383 * 384 * @throws ClosedByInterruptException 385 * If another thread interrupts the current thread 386 * while the read operation is in progress, thereby 387 * closing the channel and setting the current thread's 388 * interrupt status 389 * 390 * @throws SecurityException 391 * If a security manager has been installed 392 * and it does not permit datagrams to be accepted 393 * from the datagram's sender 394 * 395 * @throws IOException 396 * If some other I/O error occurs 397 */ 398 public abstract SocketAddress receive(ByteBuffer dst) throws IOException; 399 400 /** 401 * Sends a datagram via this channel. 402 * 403 * <p> If this channel is in non-blocking mode and there is sufficient room 404 * in the underlying output buffer, or if this channel is in blocking mode 405 * and sufficient room becomes available, then the remaining bytes in the 406 * given buffer are transmitted as a single datagram to the given target 407 * address. 408 * 409 * <p> The datagram is transferred from the byte buffer as if by a regular 410 * {@link WritableByteChannel#write(java.nio.ByteBuffer) write} operation. 411 * 412 * <p> This method performs exactly the same security checks as the {@link 413 * java.net.DatagramSocket#send send} method of the {@link 414 * java.net.DatagramSocket} class. That is, if the socket is not connected 415 * to a specific remote address and a security manager has been installed 416 * then for each datagram sent this method verifies that the target address 417 * and port number are permitted by the security manager's {@link 418 * java.lang.SecurityManager#checkConnect checkConnect} method. The 419 * overhead of this security check can be avoided by first connecting the 420 * socket via the {@link #connect connect} method. 421 * 422 * <p> This method may be invoked at any time. If another thread has 423 * already initiated a write operation upon this channel, however, then an 424 * invocation of this method will block until the first operation is 425 * complete. If this channel's socket is not bound then this method will 426 * first cause the socket to be bound to an address that is assigned 427 * automatically, as if by invoking the {@link #bind bind} method with a 428 * parameter of {@code null}. </p> 429 * 430 * @param src 431 * The buffer containing the datagram to be sent 432 * 433 * @param target 434 * The address to which the datagram is to be sent 435 * 436 * @return The number of bytes sent, which will be either the number 437 * of bytes that were remaining in the source buffer when this 438 * method was invoked or, if this channel is non-blocking, may be 439 * zero if there was insufficient room for the datagram in the 440 * underlying output buffer 441 * 442 * @throws ClosedChannelException 443 * If this channel is closed 444 * 445 * @throws AsynchronousCloseException 446 * If another thread closes this channel 447 * while the read operation is in progress 448 * 449 * @throws ClosedByInterruptException 450 * If another thread interrupts the current thread 451 * while the read operation is in progress, thereby 452 * closing the channel and setting the current thread's 453 * interrupt status 454 * 455 * @throws SecurityException 456 * If a security manager has been installed 457 * and it does not permit datagrams to be sent 458 * to the given address 459 * 460 * @throws IOException 461 * If some other I/O error occurs 462 */ 463 public abstract int send(ByteBuffer src, SocketAddress target) 464 throws IOException; 465 466 467 // -- ByteChannel operations -- 468 469 /** 470 * Reads a datagram from this channel. 471 * 472 * <p> This method may only be invoked if this channel's socket is 473 * connected, and it only accepts datagrams from the socket's peer. If 474 * there are more bytes in the datagram than remain in the given buffer 475 * then the remainder of the datagram is silently discarded. Otherwise 476 * this method behaves exactly as specified in the {@link 477 * ReadableByteChannel} interface. </p> 478 * 479 * @throws NotYetConnectedException 480 * If this channel's socket is not connected 481 */ 482 public abstract int read(ByteBuffer dst) throws IOException; 483 484 /** 485 * Reads a datagram from this channel. 486 * 487 * <p> This method may only be invoked if this channel's socket is 488 * connected, and it only accepts datagrams from the socket's peer. If 489 * there are more bytes in the datagram than remain in the given buffers 490 * then the remainder of the datagram is silently discarded. Otherwise 491 * this method behaves exactly as specified in the {@link 492 * ScatteringByteChannel} interface. </p> 493 * 494 * @throws NotYetConnectedException 495 * If this channel's socket is not connected 496 */ 497 public abstract long read(ByteBuffer[] dsts, int offset, int length) 498 throws IOException; 499 500 /** 501 * Reads a datagram from this channel. 502 * 503 * <p> This method may only be invoked if this channel's socket is 504 * connected, and it only accepts datagrams from the socket's peer. If 505 * there are more bytes in the datagram than remain in the given buffers 506 * then the remainder of the datagram is silently discarded. Otherwise 507 * this method behaves exactly as specified in the {@link 508 * ScatteringByteChannel} interface. </p> 509 * 510 * @throws NotYetConnectedException 511 * If this channel's socket is not connected 512 */ 513 public final long read(ByteBuffer[] dsts) throws IOException { 514 return read(dsts, 0, dsts.length); 515 } 516 517 /** 518 * Writes a datagram to this channel. 519 * 520 * <p> This method may only be invoked if this channel's socket is 521 * connected, in which case it sends datagrams directly to the socket's 522 * peer. Otherwise it behaves exactly as specified in the {@link 523 * WritableByteChannel} interface. </p> 524 * 525 * @throws NotYetConnectedException 526 * If this channel's socket is not connected 527 */ 528 public abstract int write(ByteBuffer src) throws IOException; 529 530 /** 531 * Writes a datagram to this channel. 532 * 533 * <p> This method may only be invoked if this channel's socket is 534 * connected, in which case it sends datagrams directly to the socket's 535 * peer. Otherwise it behaves exactly as specified in the {@link 536 * GatheringByteChannel} interface. </p> 537 * 538 * @return The number of bytes sent, which will be either the number 539 * of bytes that were remaining in the source buffer when this 540 * method was invoked or, if this channel is non-blocking, may be 541 * zero if there was insufficient room for the datagram in the 542 * underlying output buffer 543 * 544 * @throws NotYetConnectedException 545 * If this channel's socket is not connected 546 */ 547 public abstract long write(ByteBuffer[] srcs, int offset, int length) 548 throws IOException; 549 550 /** 551 * Writes a datagram to this channel. 552 * 553 * <p> This method may only be invoked if this channel's socket is 554 * connected, in which case it sends datagrams directly to the socket's 555 * peer. Otherwise it behaves exactly as specified in the {@link 556 * GatheringByteChannel} interface. </p> 557 * 558 * @return The number of bytes sent, which will be either the number 559 * of bytes that were remaining in the source buffer when this 560 * method was invoked or, if this channel is non-blocking, may be 561 * zero if there was insufficient room for the datagram in the 562 * underlying output buffer 563 * 564 * @throws NotYetConnectedException 565 * If this channel's socket is not connected 566 */ 567 public final long write(ByteBuffer[] srcs) throws IOException { 568 return write(srcs, 0, srcs.length); 569 } 570 571 /** 572 * {@inheritDoc} 573 * <p> 574 * If there is a security manager set, its {@code checkConnect} method is 575 * called with the local address and {@code -1} as its arguments to see 576 * if the operation is allowed. If the operation is not allowed, 577 * a {@code SocketAddress} representing the 578 * {@link java.net.InetAddress#getLoopbackAddress loopback} address and the 579 * local port of the channel's socket is returned. 580 * 581 * @return The {@code SocketAddress} that the socket is bound to, or the 582 * {@code SocketAddress} representing the loopback address if 583 * denied by the security manager, or {@code null} if the 584 * channel's socket is not bound 585 * 586 * @throws ClosedChannelException {@inheritDoc} 587 * @throws IOException {@inheritDoc} 588 */ 589 @Override 590 public abstract SocketAddress getLocalAddress() throws IOException; 591 592 } 593