Class DatagramChannel
- All Implemented Interfaces:
Closeable,AutoCloseable,ByteChannel,Channel,GatheringByteChannel,InterruptibleChannel,MulticastChannel,NetworkChannel,ReadableByteChannel,ScatteringByteChannel,WritableByteChannel
A datagram channel is created by invoking one of the open methods
of this class. It is not possible to create a channel for an arbitrary,
pre-existing datagram socket. A newly-created datagram channel is open but not
connected. A datagram channel 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 are otherwise performed as part of
every send and receive operation. A datagram 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, a datagram channel remains connected until it is
disconnected or closed. Whether or not a datagram channel is connected may
be determined by invoking its isConnected method.
Socket options are configured using the setOption method. A datagram channel to an Internet Protocol socket supports
the following options:
Additional (implementation specific) options may also be supported.
Option Name Description SO_SNDBUFThe size of the socket send buffer SO_RCVBUFThe size of the socket receive buffer SO_REUSEADDRRe-use address SO_BROADCASTAllow transmission of broadcast datagrams IP_TOSThe Type of Service (ToS) octet in the Internet Protocol (IP) header IP_MULTICAST_IFThe network interface for Internet Protocol (IP) multicast datagrams IP_MULTICAST_TTLThe time-to-live for Internet Protocol (IP) multicast datagrams IP_MULTICAST_LOOPLoopback for Internet Protocol (IP) multicast datagrams
Datagram channels are safe for use by multiple concurrent threads. They support concurrent reading and writing, though at most one thread may be reading and at most one thread may be writing at any given time.
- Since:
- 1.4
-
Constructor Summary
ConstructorsModifierConstructorDescriptionprotectedDatagramChannel(SelectorProvider provider) Initializes a new instance of this class. -
Method Summary
Modifier and TypeMethodDescriptionabstract DatagramChannelbind(SocketAddress local) Binds the channel's socket to a local address.abstract DatagramChannelconnect(SocketAddress remote) Connects this channel's socket.abstract DatagramChannelDisconnects this channel's socket.abstract SocketAddressReturns the socket address that this channel's socket is bound to.abstract SocketAddressReturns the remote address to which this channel's socket is connected.abstract booleanTells whether or not this channel's socket is connected.static DatagramChannelopen()Opens a datagram channel.static DatagramChannelopen(ProtocolFamily family) Opens a datagram channel.abstract intread(ByteBuffer dst) Reads a datagram from this channel.final longread(ByteBuffer[] dsts) Reads a datagram from this channel.abstract longread(ByteBuffer[] dsts, int offset, int length) Reads a datagram from this channel.abstract SocketAddressreceive(ByteBuffer dst) Receives a datagram via this channel.abstract intsend(ByteBuffer src, SocketAddress target) Sends a datagram via this channel.abstract <T> DatagramChannelsetOption(SocketOption<T> name, T value) Sets the value of a socket option.abstract DatagramSocketsocket()Retrieves a datagram socket associated with this channel.final intvalidOps()Returns an operation set identifying this channel's supported operations.abstract intwrite(ByteBuffer src) Writes a datagram to this channel.final longwrite(ByteBuffer[] srcs) Writes a datagram to this channel.abstract longwrite(ByteBuffer[] srcs, int offset, int length) Writes a datagram to this channel.Methods declared in class java.nio.channels.spi.AbstractSelectableChannel
blockingLock, configureBlocking, implCloseChannel, implCloseSelectableChannel, implConfigureBlocking, isBlocking, isRegistered, keyFor, provider, registerMethods declared in class java.nio.channels.SelectableChannel
registerMethods declared in class java.nio.channels.spi.AbstractInterruptibleChannel
begin, close, end, isOpenMethods declared in class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, waitMethods declared in interface java.nio.channels.MulticastChannel
close, join, joinMethods declared in interface java.nio.channels.NetworkChannel
getOption, supportedOptions
-
Constructor Details
-
DatagramChannel
Initializes a new instance of this class.- Parameters:
provider- The provider that created this channel
-
-
Method Details
-
open
Opens a datagram channel.The new channel is created by invoking the
openDatagramChannelmethod of the system-wide defaultSelectorProviderobject. The channel will not be connected.The
ProtocolFamilyof the channel's socket is platform (and possibly configuration) dependent and therefore unspecified. Theopenallows the protocol family to be selected when opening a datagram channel, and should be used to open datagram channels that are intended for Internet Protocol multicasting.- Returns:
- A new datagram channel
- Throws:
IOException- If an I/O error occurs- See Also:
-
open
Opens a datagram channel.The
familyparameter is used to specify theProtocolFamily. If the datagram channel is to be used for IP multicasting then this should correspond to the address type of the multicast groups that this channel will join.The new channel is created by invoking the
openDatagramChannelmethod of the system-wide defaultSelectorProviderobject. The channel will not be connected.- API Note:
- Unix domain sockets are not supported.
- Parameters:
family- The protocol family- Returns:
- A new datagram channel
- Throws:
UnsupportedOperationException- If the specified protocol family is not supported. For example, suppose the parameter is specified asStandardProtocolFamily.INET6but IPv6 is not enabled on the platform.IOException- If an I/O error occurs- Since:
- 1.7
- See Also:
-
validOps
public final int validOps()Returns an operation set identifying this channel's supported operations.Datagram channels support reading and writing, so this method returns
(SelectionKey.OP_READ|SelectionKey.OP_WRITE).- Specified by:
validOpsin classSelectableChannel- Returns:
- The valid-operation set
-
bind
Description copied from interface:NetworkChannelBinds 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
localparameter has the valuenullthen the socket will be bound to an address that is assigned automatically.- Specified by:
bindin interfaceNetworkChannel- Parameters:
local- The address to bind the socket, ornullto bind the socket to an automatically assigned socket address- Returns:
- This channel
- Throws:
AlreadyBoundException- If the socket is already boundUnsupportedAddressTypeException- If the type of the given address is not supportedClosedChannelException- If the channel is closedIOException- If some other I/O error occursSecurityException- If a security manager has been installed and itscheckListenmethod denies the operation- Since:
- 1.7
- See Also:
-
setOption
Description copied from interface:NetworkChannelSets the value of a socket option.- Specified by:
setOptionin interfaceNetworkChannel- Type Parameters:
T- The type of the socket option value- Parameters:
name- The socket optionvalue- The value of the socket option. A value ofnullmay be a valid value for some socket options.- Returns:
- This channel
- Throws:
UnsupportedOperationException- If the socket option is not supported by this channelIllegalArgumentException- If the value is not a valid value for this socket optionClosedChannelException- If this channel is closedIOException- If an I/O error occurs- Since:
- 1.7
- See Also:
-
socket
Retrieves a datagram socket associated with this channel.- Returns:
- A datagram socket associated with this channel
-
isConnected
public abstract boolean isConnected()Tells whether or not this channel's socket is connected.- Returns:
trueif, and only if, this channel's socket isopenand connected
-
connect
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. Datagrams in the channel's socket receive buffer, which have not been received before invoking this method, may be discarded. The channel's socket remains connected until it is explicitly disconnected or until it is closed.
This method performs exactly the same security checks as the
connectmethod of theDatagramSocketclass. That is, if a security manager has been installed then this method verifies that itscheckAcceptandcheckConnectmethods permit datagrams to be received from and sent to, respectively, the given remote address. Once connected, no further security checks are performed for datagrams received from, or sent to, the given remote address. Care should be taken to ensure that a connected datagram channel is not shared with untrusted code.This method may be invoked at any time. If another thread has already initiated a read or write operation upon this channel, then an invocation of this method will block until any such operation is complete. If this channel's socket is not bound then this method will first cause the socket to be bound to an address that is assigned automatically, as if invoking the
bindmethod with a parameter ofnull.- Parameters:
remote- The remote address to which this channel is to be connected- Returns:
- This datagram channel
- Throws:
AlreadyConnectedException- If this channel is already connectedClosedChannelException- If this channel is closedAsynchronousCloseException- If another thread closes this channel while the connect operation is in progressClosedByInterruptException- If another thread interrupts the current thread while the connect operation is in progress, thereby closing the channel and setting the current thread's interrupt statusUnresolvedAddressException- If the given remote address is not fully resolvedUnsupportedAddressTypeException- If the type of the given remote address is not supportedSecurityException- If a security manager has been installed and it does not permit access to the given remote address, or if unbound, the security managercheckListenmethod denies the operationIOException- If some other I/O error occurs
-
disconnect
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. If another thread has already initiated a read or write operation upon this channel, then an invocation of this method will block until any such operation is complete.
If this channel's socket is not connected, or if the channel is closed, then invoking this method has no effect.
- API Note:
- If this method throws an IOException, the channel's socket may be left in an unspecified state. It is strongly recommended that the channel be closed when disconnect fails.
- Returns:
- This datagram channel
- Throws:
IOException- If some other I/O error occurs
-
getRemoteAddress
Returns the remote address to which this channel's socket is connected.- Returns:
- The remote address;
nullif the channel's socket is not connected - Throws:
ClosedChannelException- If the channel is closedIOException- If an I/O error occurs- Since:
- 1.7
-
receive
Receives a datagram via this channel.If a datagram is immediately available, or if this channel is in blocking mode and one eventually becomes available, then the datagram is copied into the given byte buffer and its source address is returned. If this channel is in non-blocking mode and a datagram is not immediately available then this method immediately returns
null.The datagram is transferred into the given byte buffer starting at its current position, as if by a regular
readoperation. 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.This method performs exactly the same security checks as the
receivemethod of theDatagramSocketclass. That is, if the socket is not connected to a specific remote address and a security manager has been installed then for each datagram received this method verifies that the source's address and port number are permitted by the security manager'scheckAcceptmethod. Datagrams that are not permitted by the security manager are silently discarded. The overhead of this security check can be avoided by first connecting the socket via theconnectmethod.This method may be invoked at any time. If another thread has already initiated a read operation upon this channel, however, then an invocation of this method will block until the first operation is complete. If this channel's socket is not bound then this method will first cause the socket to be bound to an address that is assigned automatically, as if invoking the
bindmethod with a parameter ofnull.- Parameters:
dst- The buffer into which the datagram is to be transferred- Returns:
- The datagram's source address,
or
nullif this channel is in non-blocking mode and no datagram was immediately available - Throws:
IllegalArgumentException- If the buffer is read-onlyClosedChannelException- If this channel is closedAsynchronousCloseException- If another thread closes this channel while the read operation is in progressClosedByInterruptException- If another thread interrupts the current thread while the read operation is in progress, thereby closing the channel and setting the current thread's interrupt statusSecurityException- If unbound, and a security manager has been installed and itscheckListenmethod denies the operationIOException- If some other I/O error occurs
-
send
Sends a datagram via this channel.If this channel is in non-blocking mode and there is sufficient room in the underlying output buffer, or if this channel is in blocking mode and sufficient room becomes available, then the remaining bytes in the given buffer are transmitted as a single datagram to the given target address.
The datagram is transferred from the byte buffer as if by a regular
writeoperation.This method performs exactly the same security checks as the
sendmethod of theDatagramSocketclass. That is, if the socket is not connected to a specific remote address and a security manager has been installed then for each datagram sent this method verifies that the target address and port number are permitted by the security manager'scheckConnectmethod. The overhead of this security check can be avoided by first connecting the socket via theconnectmethod.This method may be invoked at any time. If another thread has already initiated a write operation upon this channel, however, then an invocation of this method will block until the first operation is complete. If this channel's socket is not bound then this method will first cause the socket to be bound to an address that is assigned automatically, as if by invoking the
bindmethod with a parameter ofnull.- Parameters:
src- The buffer containing the datagram to be senttarget- The address to which the datagram is to be sent- Returns:
- The number of bytes sent, which will be either the number of bytes that were remaining in the source buffer when this method was invoked or, if this channel is non-blocking, may be zero if there was insufficient room for the datagram in the underlying output buffer
- Throws:
AlreadyConnectedException- If this channel is connected to a different address from that specified bytargetClosedChannelException- If this channel is closedAsynchronousCloseException- If another thread closes this channel while the read operation is in progressClosedByInterruptException- If another thread interrupts the current thread while the read operation is in progress, thereby closing the channel and setting the current thread's interrupt statusUnresolvedAddressException- If the given remote address is not fully resolvedUnsupportedAddressTypeException- If the type of the given remote address is not supportedSecurityException- If a security manager has been installed and it does not permit datagrams to be sent to the given address, or if unbound, and the security manager'scheckListenmethod denies the operationIOException- If some other I/O error occurs
-
read
Reads a datagram from this channel.This method may only be invoked if this channel's socket is connected, and it only accepts datagrams from the socket's peer. If there are more bytes in the datagram than remain in the given buffer then the remainder of the datagram is silently discarded. Otherwise this method behaves exactly as specified in the
ReadableByteChannelinterface.- Specified by:
readin interfaceReadableByteChannel- Parameters:
dst- The buffer into which bytes are to be transferred- Returns:
- The number of bytes read, possibly zero, or
-1if the channel has reached end-of-stream - Throws:
NotYetConnectedException- If this channel's socket is not connectedClosedChannelException- If this channel is closedAsynchronousCloseException- If another thread closes this channel while the read operation is in progressClosedByInterruptException- If another thread interrupts the current thread while the read operation is in progress, thereby closing the channel and setting the current thread's interrupt statusIOException- If some other I/O error occurs
-
read
Reads a datagram from this channel.This method may only be invoked if this channel's socket is connected, and it only accepts datagrams from the socket's peer. If there are more bytes in the datagram than remain in the given buffers then the remainder of the datagram is silently discarded. Otherwise this method behaves exactly as specified in the
ScatteringByteChannelinterface.- Specified by:
readin interfaceScatteringByteChannel- Parameters:
dsts- The buffers into which bytes are to be transferredoffset- The offset within the buffer array of the first buffer into which bytes are to be transferred; must be non-negative and no larger thandsts.lengthlength- The maximum number of buffers to be accessed; must be non-negative and no larger thandsts.length-offset- Returns:
- The number of bytes read, possibly zero,
or
-1if the channel has reached end-of-stream - Throws:
NotYetConnectedException- If this channel's socket is not connectedClosedChannelException- If this channel is closedAsynchronousCloseException- If another thread closes this channel while the read operation is in progressClosedByInterruptException- If another thread interrupts the current thread while the read operation is in progress, thereby closing the channel and setting the current thread's interrupt statusIOException- If some other I/O error occurs
-
read
Reads a datagram from this channel.This method may only be invoked if this channel's socket is connected, and it only accepts datagrams from the socket's peer. If there are more bytes in the datagram than remain in the given buffers then the remainder of the datagram is silently discarded. Otherwise this method behaves exactly as specified in the
ScatteringByteChannelinterface.- Specified by:
readin interfaceScatteringByteChannel- Parameters:
dsts- The buffers into which bytes are to be transferred- Returns:
- The number of bytes read, possibly zero,
or
-1if the channel has reached end-of-stream - Throws:
NotYetConnectedException- If this channel's socket is not connectedClosedChannelException- If this channel is closedAsynchronousCloseException- If another thread closes this channel while the read operation is in progressClosedByInterruptException- If another thread interrupts the current thread while the read operation is in progress, thereby closing the channel and setting the current thread's interrupt statusIOException- If some other I/O error occurs
-
write
Writes a datagram to this channel.This method may only be invoked if this channel's socket is connected, in which case it sends datagrams directly to the socket's peer. Otherwise it behaves exactly as specified in the
WritableByteChannelinterface.- Specified by:
writein interfaceWritableByteChannel- Parameters:
src- The buffer from which bytes are to be retrieved- Returns:
- The number of bytes written, possibly zero
- Throws:
NotYetConnectedException- If this channel's socket is not connectedClosedChannelException- If this channel is closedAsynchronousCloseException- If another thread closes this channel while the write operation is in progressClosedByInterruptException- If another thread interrupts the current thread while the write operation is in progress, thereby closing the channel and setting the current thread's interrupt statusIOException- If some other I/O error occurs
-
write
Writes a datagram to this channel.This method may only be invoked if this channel's socket is connected, in which case it sends datagrams directly to the socket's peer. Otherwise it behaves exactly as specified in the
GatheringByteChannelinterface.- Specified by:
writein interfaceGatheringByteChannel- Parameters:
srcs- The buffers from which bytes are to be retrievedoffset- The offset within the buffer array of the first buffer from which bytes are to be retrieved; must be non-negative and no larger thansrcs.lengthlength- The maximum number of buffers to be accessed; must be non-negative and no larger thansrcs.length-offset- Returns:
- The number of bytes sent, which will be either the number of bytes that were remaining in the source buffer when this method was invoked or, if this channel is non-blocking, may be zero if there was insufficient room for the datagram in the underlying output buffer
- Throws:
NotYetConnectedException- If this channel's socket is not connectedClosedChannelException- If this channel is closedAsynchronousCloseException- If another thread closes this channel while the write operation is in progressClosedByInterruptException- If another thread interrupts the current thread while the write operation is in progress, thereby closing the channel and setting the current thread's interrupt statusIOException- If some other I/O error occurs
-
write
Writes a datagram to this channel.This method may only be invoked if this channel's socket is connected, in which case it sends datagrams directly to the socket's peer. Otherwise it behaves exactly as specified in the
GatheringByteChannelinterface.- Specified by:
writein interfaceGatheringByteChannel- Parameters:
srcs- The buffers from which bytes are to be retrieved- Returns:
- The number of bytes sent, which will be either the number of bytes that were remaining in the source buffer when this method was invoked or, if this channel is non-blocking, may be zero if there was insufficient room for the datagram in the underlying output buffer
- Throws:
NotYetConnectedException- If this channel's socket is not connectedClosedChannelException- If this channel is closedAsynchronousCloseException- If another thread closes this channel while the write operation is in progressClosedByInterruptException- If another thread interrupts the current thread while the write operation is in progress, thereby closing the channel and setting the current thread's interrupt statusIOException- If some other I/O error occurs
-
getLocalAddress
Returns the socket address that this channel's socket is bound to.Where the channel is
boundto an Internet Protocol socket address then the return value from this method is of typeInetSocketAddress.If the channel's socket was initially bound to the wildcard address and is now
connected, then the address returned may be the local address selected as the source address for datagrams sent via this channel instead of the wildcard address. Whendisconnect()is called, the bound address reverts to the wildcard address.If there is a security manager set, its
checkConnectmethod is called with the local address and-1as its arguments to see if the operation is allowed. If the operation is not allowed, aSocketAddressrepresenting theloopbackaddress and the local port of the channel's socket is returned.- Specified by:
getLocalAddressin interfaceNetworkChannel- Returns:
- The
SocketAddressthat the socket is bound to, or theSocketAddressrepresenting the loopback address if denied by the security manager, ornullif the channel's socket is not bound - Throws:
ClosedChannelException- If the channel is closedIOException- If an I/O error occurs
-