Spec-Zone .ru
спецификации, руководства, описания, API
Please note that this documentation is not final and is subject to change.

Java™ Platform
Standard Ed. 7

DRAFT ea-b84

java.nio.channels
Class AsynchronousDatagramChannel

java.lang.Object
  extended by java.nio.channels.AsynchronousDatagramChannel
All Implemented Interfaces:
Closeable, AsynchronousByteChannel, AsynchronousChannel, Channel, MulticastChannel, NetworkChannel

public abstract class AsynchronousDatagramChannel
extends Object
implements AsynchronousByteChannel, MulticastChannel

An asynchronous channel for datagram-oriented sockets.

An asynchronous datagram channel is created by invoking one of the open methods defined by this class. It is not possible to create a channel for an arbitrary, pre-existing datagram socket. A newly-created asynchronous datagram channel is open but not connected. It need not be connected in order for the send and receive methods to be used. A datagram channel may be connected, by invoking its connect method, in order to avoid the overhead of the security checks that are otherwise performed as part of every send and receive operation when a security manager is set. The channel must be connected in order to use the read and write methods, since those methods do not accept or return socket addresses. Once connected, an asynchronous datagram channel remains connected until it is disconnected or closed.

Socket options are configured using the setOption method. An asynchronous datagram channel to an Internet Protocol (IP) socket supports the following options:

Option Name Description
SO_SNDBUF The size of the socket send buffer
SO_RCVBUF The size of the socket receive buffer
SO_REUSEADDR Re-use address
SO_BROADCAST Allow transmission of broadcast datagrams
IP_TOS The Type of Service (ToS) octet in the Internet Protocol (IP) header
IP_MULTICAST_IF The network interface for Internet Protocol (IP) multicast datagrams
IP_MULTICAST_TTL The time-to-live for Internet Protocol (IP) multicast datagrams
IP_MULTICAST_LOOP Loopback for Internet Protocol (IP) multicast datagrams
Additional (implementation specific) options may also be supported.

Asynchronous datagram channels allow more than one read/receive and write/send to be oustanding at any given time.

Usage Example:

  final AsynchronousDatagramChannel dc = AsynchronousDatagramChannel.open()
      .bind(new InetSocketAddress(4000));

  // print the source address of all packets that we receive
  dc.receive(buffer, buffer, new CompletionHandler<SocketAddress,ByteBuffer>() {
      public void completed(SocketAddress sa, ByteBuffer buffer) {
          System.out.println(sa);
          buffer.clear();
          dc.receive(buffer, buffer, this);
      }
      public void failed(Throwable exc, ByteBuffer buffer) {
          ...
      }
  });
 

Since:
1.7

Constructor Summary
Modifier Constructor and Description
protected AsynchronousDatagramChannel(AsynchronousChannelProvider provider)
          Initializes a new instance of this class.
 
Method Summary
Modifier and Type Method and Description
abstract  AsynchronousDatagramChannel bind(SocketAddress local)
          Binds the channel's socket to a local address.
abstract  AsynchronousDatagramChannel connect(SocketAddress remote)
          Connects this channel's socket.
abstract  AsynchronousDatagramChannel disconnect()
          Disconnects this channel's socket.
abstract  SocketAddress getRemoteAddress()
          Returns the remote address to which this channel is connected.
static AsynchronousDatagramChannel open()
          Opens an asynchronous datagram channel.
static AsynchronousDatagramChannel open(ProtocolFamily family, AsynchronousChannelGroup group)
          Opens an asynchronous datagram channel.
 AsynchronousChannelProvider provider()
          Returns the provider that created this channel.
abstract  Future<Integer> read(ByteBuffer dst)
          Reads a sequence of bytes from this channel into the given buffer.
<A> void
read(ByteBuffer dst, A attachment, CompletionHandler<Integer,? super A> handler)
          Reads a sequence of bytes from this channel into the given buffer.
abstract
<A> void
read(ByteBuffer dst, long timeout, TimeUnit unit, A attachment, CompletionHandler<Integer,? super A> handler)
          Receives a datagram via this channel.
abstract  Future<SocketAddress> receive(ByteBuffer dst)
          Receives a datagram via this channel.
<A> void
receive(ByteBuffer dst, A attachment, CompletionHandler<SocketAddress,? super A> handler)
          Receives a datagram via this channel.
abstract
<A> void
receive(ByteBuffer dst, long timeout, TimeUnit unit, A attachment, CompletionHandler<SocketAddress,? super A> handler)
          Receives a datagram via this channel.
abstract  Future<Integer> send(ByteBuffer src, SocketAddress target)
          Sends a datagram via this channel.
abstract
<A> void
send(ByteBuffer src, SocketAddress target, A attachment, CompletionHandler<Integer,? super A> handler)
          Sends a datagram via this channel.
abstract
<T> AsynchronousDatagramChannel
setOption(SocketOption<T> name, T value)
          Sets the value of a socket option.
abstract  Future<Integer> write(ByteBuffer src)
          Writes a sequence of bytes to this channel from the given buffer.
abstract
<A> void
write(ByteBuffer src, A attachment, CompletionHandler<Integer,? super A> handler)
          Writes a sequence of bytes to this channel from the given buffer.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 
Methods inherited from interface java.nio.channels.AsynchronousChannel
close
 
Methods inherited from interface java.nio.channels.MulticastChannel
close, join, join
 
Methods inherited from interface java.nio.channels.NetworkChannel
getLocalAddress, getOption, supportedOptions
 
Methods inherited from interface java.nio.channels.Channel
isOpen
 

Constructor Detail

AsynchronousDatagramChannel

protected AsynchronousDatagramChannel(AsynchronousChannelProvider provider)
Initializes a new instance of this class.

Method Detail

provider

public final AsynchronousChannelProvider provider()
Returns the provider that created this channel.


open

public static AsynchronousDatagramChannel open(ProtocolFamily family,
                                               AsynchronousChannelGroup group)
                                        throws IOException
Opens an asynchronous datagram channel.

The new channel is created by invoking the openAsynchronousDatagramChannel method on the AsynchronousChannelProvider object that created the given group (or the default provider where group is null).

The family parameter is used to specify the ProtocolFamily. If the datagram channel is to be used for Internet Protocol multicasting then this parameter should correspond to the address type of the multicast groups that this channel will join.

Parameters:
family - The protocol family, or null to use the default protocol family
group - The group to which the newly constructed channel should be bound, or null for the default group
Returns:
A new asynchronous datagram channel
Throws:
UnsupportedOperationException - If the specified protocol family is not supported. For example, suppose the parameter is specified as INET6 but IPv6 is not enabled on the platform.
ShutdownChannelGroupException - The specified group is shutdown
IOException - If an I/O error occurs

open

public static AsynchronousDatagramChannel open()
                                        throws IOException
Opens an asynchronous datagram channel.

This method returns an asynchronous datagram channel that is bound to the default group. This method is equivalent to evaluating the expression:

 open((ProtocolFamily)null, (AsynchronousChannelGroup)null);
 

Returns:
A new asynchronous datagram channel
Throws:
IOException - If an I/O error occurs

bind

public abstract AsynchronousDatagramChannel bind(SocketAddress local)
                                          throws IOException
Description copied from interface: NetworkChannel
Binds the channel's socket to a local address.

This method is used to establish an association between the socket and a local address. Once an association is established then the socket remains bound until the channel is closed. If the local parameter has the value null then the socket will be bound to an address that is assigned automatically.

Specified by:
bind in interface NetworkChannel
Parameters:
local - The address to bind the socket, or null to bind the socket to an automatically assigned socket address
Returns:
This channel
Throws:
AlreadyBoundException - If the socket is already bound
UnsupportedAddressTypeException - If the type of the given address is not supported
ClosedChannelException - If the channel is closed
IOException - If some other I/O error occurs
SecurityException - If a security manager has been installed and its checkListen method denies the operation
See Also:
NetworkChannel.getLocalAddress()

setOption

public abstract <T> AsynchronousDatagramChannel setOption(SocketOption<T> name,
                                                          T value)
                                               throws IOException
Description copied from interface: NetworkChannel
Sets the value of a socket option.

Specified by:
setOption in interface NetworkChannel
Parameters:
name - The socket option
value - The value of the socket option. A value of null may be a valid value for some socket options.
Returns:
This channel
Throws:
IllegalArgumentException - If the value is not a valid value for this socket option
ClosedChannelException - If this channel is closed
IOException - If an I/O error occurs
See Also:
StandardSocketOption

getRemoteAddress

public abstract SocketAddress getRemoteAddress()
                                        throws IOException
Returns the remote address to which this channel is connected.

Where the channel is connected to an Internet Protocol socket address then the return value from this method is of type InetSocketAddress.

Returns:
The remote address; null if the channel's socket is not connected
Throws:
ClosedChannelException - If the channel is closed
IOException - If an I/O error occurs

connect

public abstract AsynchronousDatagramChannel connect(SocketAddress remote)
                                             throws IOException
Connects this channel's socket.

The channel's socket is configured so that it only receives datagrams from, and sends datagrams to, the given remote peer address. Once connected, datagrams may not be received from or sent to any other address. A datagram socket remains connected until it is explicitly disconnected or until it is closed.

This method performs exactly the same security checks as the connect method of the DatagramSocket class. That is, if a security manager has been installed then this method verifies that its checkAccept and checkConnect methods permit datagrams to be received from and sent to, respectively, the given remote address.

This method may be invoked at any time. Whether it has any effect on outstanding read or write operations is implementation specific and therefore not specified.

Parameters:
remote - The remote address to which this channel is to be connected
Returns:
This datagram channel
Throws:
ClosedChannelException - If this channel is closed
SecurityException - If a security manager has been installed and it does not permit access to the given remote address
IOException - If some other I/O error occurs

disconnect

public abstract AsynchronousDatagramChannel disconnect()
                                                throws IOException
Disconnects this channel's socket.

The channel's socket is configured so that it can receive datagrams from, and sends datagrams to, any remote address so long as the security manager, if installed, permits it.

This method may be invoked at any time. Whether it has any effect on outstanding read or write operations is implementation specific and therefore not specified.

Returns:
This datagram channel
Throws:
IOException - If some other I/O error occurs

receive

public abstract <A> void receive(ByteBuffer dst,
                                 long timeout,
                                 TimeUnit unit,
                                 A attachment,
                                 CompletionHandler<SocketAddress,? super A> handler)
Receives a datagram via this channel.

This method initiates the receiving of a datagram into the given buffer. The handler parameter is a completion handler that is invoked when the receive operation completes (or fails). The result passed to the completion handler is the datagram's source address.

The datagram is transferred into the given byte buffer starting at its current position, as if by a regular read operation. If there are fewer bytes remaining in the buffer than are required to hold the datagram then the remainder of the datagram is silently discarded.

If a timeout is specified and the timeout elapses before the operation completes then the operation completes with the exception InterruptedByTimeoutException. When a timeout elapses then the state of the ByteBuffer is not defined. The buffers should be discarded or at least care must be taken to ensure that the buffer is not accessed while the channel remains open.

When a security manager has been installed and the channel is not connected, then it verifies that the source's address and port number are permitted by the security manager's checkAccept method. The permission check is performed with privileges that are restricted by the calling context of this method. If the permission check fails then the operation completes with a SecurityException. The overhead of this security check can be avoided by first connecting the socket via the connect method.

Parameters:
dst - The buffer into which the datagram is to be transferred
timeout - The timeout, or 0L for no timeout
unit - The time unit of the timeout argument
attachment - The object to attach to the I/O operation; can be null
handler - The handler for consuming the result
Throws:
IllegalArgumentException - If the timeout is negative or the buffer is read-only
ShutdownChannelGroupException - If the channel group has terminated

receive

public final <A> void receive(ByteBuffer dst,
                              A attachment,
                              CompletionHandler<SocketAddress,? super A> handler)
Receives a datagram via this channel.

This method initiates the receiving of a datagram into the given buffer. The handler parameter is a completion handler that is invoked when the receive operation completes (or fails). The result passed to the completion handler is the datagram's source address.

This method is equivalent to invoking receive(ByteBuffer,long,TimeUnit,Object,CompletionHandler) with a timeout of 0L.

Parameters:
dst - The buffer into which the datagram is to be transferred
attachment - The object to attach to the I/O operation; can be null
handler - The handler for consuming the result
Throws:
IllegalArgumentException - If the buffer is read-only
ShutdownChannelGroupException - If the channel group has terminated

receive

public abstract Future<SocketAddress> receive(ByteBuffer dst)
Receives a datagram via this channel.

This method initiates the receiving of a datagram into the given buffer. The method behaves in exactly the same manner as the receive(ByteBuffer,Object,CompletionHandler) method except that instead of specifying a completion handler, this method returns a Future representing the pending result. The Future's get method returns the datagram's source address.

Parameters:
dst - The buffer into which the datagram is to be transferred
Returns:
a Future object representing the pending result
Throws:
IllegalArgumentException - If the buffer is read-only

send

public abstract <A> void send(ByteBuffer src,
                              SocketAddress target,
                              A attachment,
                              CompletionHandler<Integer,? super A> handler)
Sends a datagram via this channel.

This method initiates sending of a datagram from the given buffer to the given address. The handler parameter is a completion handler that is invoked when the send completes (or fails). The result passed to the completion handler is the number of bytes sent.

Otherwise this method works in the same manner as the AsynchronousByteChannel.write(ByteBuffer,Object,CompletionHandler) method.

Parameters:
src - The buffer containing the datagram to be sent
target - The address to which the datagram is to be sent
attachment - The object to attach to the I/O operation; can be null
handler - The handler for consuming the result
Throws:
UnresolvedAddressException - If the given remote address is not fully resolved
UnsupportedAddressTypeException - If the type of the given remote address is not supported
IllegalArgumentException - If the channel's socket is connected and is connected to an address that is not equal to target
SecurityException - If a security manager has been installed and it does not permit datagrams to be sent to the given address
ShutdownChannelGroupException - If the channel group has terminated

send

public abstract Future<Integer> send(ByteBuffer src,
                                     SocketAddress target)
Sends a datagram via this channel.

This method initiates sending of a datagram from the given buffer to the given address. The method behaves in exactly the same manner as the send(ByteBuffer,SocketAddress,Object,CompletionHandler) method except that instead of specifying a completion handler, this method returns a Future representing the pending result. The Future's get method returns the number of bytes sent.

Parameters:
src - The buffer containing the datagram to be sent
target - The address to which the datagram is to be sent
Returns:
a Future object representing the pending result
Throws:
UnresolvedAddressException - If the given remote address is not fully resolved
UnsupportedAddressTypeException - If the type of the given remote address is not supported
IllegalArgumentException - If the channel's socket is connected and is connected to an address that is not equal to target
SecurityException - If a security manager has been installed and it does not permit datagrams to be sent to the given address

read

public abstract <A> void read(ByteBuffer dst,
                              long timeout,
                              TimeUnit unit,
                              A attachment,
                              CompletionHandler<Integer,? super A> handler)
Receives a datagram via this channel.

This method initiates the receiving of a datagram into the given buffer. The handler parameter is a completion handler that is invoked when the receive operation completes (or fails). The result passed to the completion handler is number of bytes read.

This method may only be invoked if this channel is connected, and it only accepts datagrams from the peer that the channel is connected too. The datagram is transferred into the given byte buffer starting at its current position and exactly as specified in the AsynchronousByteChannel interface. If there are fewer bytes remaining in the buffer than are required to hold the datagram then the remainder of the datagram is silently discarded.

If a timeout is specified and the timeout elapses before the operation completes then the operation completes with the exception InterruptedByTimeoutException. When a timeout elapses then the state of the ByteBuffer is not defined. The buffers should be discarded or at least care must be taken to ensure that the buffer is not accessed while the channel remains open.

Parameters:
dst - The buffer into which the datagram is to be transferred
timeout - The timeout, or 0L for no timeout
unit - The time unit of the timeout argument
attachment - The object to attach to the I/O operation; can be null
handler - The handler for consuming the result
Throws:
IllegalArgumentException - If the timeout is negative or buffer is read-only
NotYetConnectedException - If this channel is not connected
ShutdownChannelGroupException - If the channel group has terminated

read

public final <A> void read(ByteBuffer dst,
                           A attachment,
                           CompletionHandler<Integer,? super A> handler)
Description copied from interface: AsynchronousByteChannel
Reads a sequence of bytes from this channel into the given buffer.

This method initiates an asynchronous read operation to read a sequence of bytes from this channel into the given buffer. The handler parameter is a completion handler that is invoked when the read operation completes (or fails). The result passed to the completion handler is the number of bytes read or -1 if no bytes could be read because the channel has reached end-of-stream.

The read operation may read up to r bytes from the channel, where r is the number of bytes remaining in the buffer, that is, dst.remaining() at the time that the read is attempted. Where r is 0, the read operation completes immediately with a result of 0 without initiating an I/O operation.

Suppose that a byte sequence of length n is read, where 0 < n <= r. This byte sequence will be transferred into the buffer so that the first byte in the sequence is at index p and the last byte is at index p + n - 1, where p is the buffer's position at the moment the read is performed. Upon completion the buffer's position will be equal to p + n; its limit will not have changed.

Buffers are not safe for use by multiple concurrent threads so care should be taken to not access the buffer until the operation has completed.

This method may be invoked at any time. Some channel types may not allow more than one read to be outstanding at any given time. If a thread initiates a read operation before a previous read operation has completed then a ReadPendingException will be thrown.

Specified by:
read in interface AsynchronousByteChannel
Parameters:
dst - The buffer into which bytes are to be transferred
attachment - The object to attach to the I/O operation; can be null
handler - The completion handler
Throws:
NotYetConnectedException - If this channel is not connected
ShutdownChannelGroupException - If the channel group has terminated

read

public abstract Future<Integer> read(ByteBuffer dst)
Description copied from interface: AsynchronousByteChannel
Reads a sequence of bytes from this channel into the given buffer.

This method initiates an asynchronous read operation to read a sequence of bytes from this channel into the given buffer. The method behaves in exactly the same manner as the read(ByteBuffer,Object,CompletionHandler) method except that instead of specifying a completion handler, this method returns a Future representing the pending result. The Future's get method returns the number of bytes read or -1 if no bytes could be read because the channel has reached end-of-stream.

Specified by:
read in interface AsynchronousByteChannel
Parameters:
dst - The buffer into which bytes are to be transferred
Returns:
A Future representing the result of the operation
Throws:
NotYetConnectedException - If this channel is not connected
ShutdownChannelGroupException - If the channel group has terminated

write

public abstract <A> void write(ByteBuffer src,
                               A attachment,
                               CompletionHandler<Integer,? super A> handler)
Description copied from interface: AsynchronousByteChannel
Writes a sequence of bytes to this channel from the given buffer.

This method initiates an asynchronous write operation to write a sequence of bytes to this channel from the given buffer. The handler parameter is a completion handler that is invoked when the write operation completes (or fails). The result passed to the completion handler is the number of bytes written.

The write operation may write up to r bytes to the channel, where r is the number of bytes remaining in the buffer, that is, src.remaining() at the time that the write is attempted. Where r is 0, the write operation completes immediately with a result of 0 without initiating an I/O operation.

Suppose that a byte sequence of length n is written, where 0 < n <= r. This byte sequence will be transferred from the buffer starting at index p, where p is the buffer's position at the moment the write is performed; the index of the last byte written will be p + n - 1. Upon completion the buffer's position will be equal to p + n; its limit will not have changed.

Buffers are not safe for use by multiple concurrent threads so care should be taken to not access the buffer until the operation has completed.

This method may be invoked at any time. Some channel types may not allow more than one write to be outstanding at any given time. If a thread initiates a write operation before a previous write operation has completed then a WritePendingException will be thrown.

Specified by:
write in interface AsynchronousByteChannel
Parameters:
src - The buffer from which bytes are to be retrieved
attachment - The object to attach to the I/O operation; can be null
handler - The completion handler object
Throws:
NotYetConnectedException - If this channel is not connected
ShutdownChannelGroupException - If the channel group has terminated

write

public abstract Future<Integer> write(ByteBuffer src)
Description copied from interface: AsynchronousByteChannel
Writes a sequence of bytes to this channel from the given buffer.

This method initiates an asynchronous write operation to write a sequence of bytes to this channel from the given buffer. The method behaves in exactly the same manner as the write(ByteBuffer,Object,CompletionHandler) method except that instead of specifying a completion handler, this method returns a Future representing the pending result. The Future's get method returns the number of bytes written.

Specified by:
write in interface AsynchronousByteChannel
Parameters:
src - The buffer from which bytes are to be retrieved
Returns:
A Future representing the result of the operation
Throws:
NotYetConnectedException - If this channel is not connected
ShutdownChannelGroupException - If the channel group has terminated

Java™ Platform
Standard Ed. 7

DRAFT ea-b84

Submit a bug or feature

Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Use is subject to license terms.

free hit counter