This class implements a communication channel based on network datagrams. Obtain a DatagramChannel by calling the static open( ) method. Call socket( ) to obtain the object on which the channel is based if you need to set any socket options to control low-level networking details.

The send( ) method sends the remaining bytes of the specified ByteBuffer to the host and port specified in the in the form of a datagram. receive( ) does the opposite: it receives a datagram, stores its content into the specified buffer (discarding any bytes that do not fit) and then returns a SocketAddress that specifies the sender of the datagram (or returns null if the channel was in nonblocking mode and no datagram was waiting).

The send( ) and receive( ) methods typically perform security checks on each invocation to see if the application has permissions to communicate with the remote host. If your application will use a DatagramChannel to exchange datagrams with a single remote host and port, use the connect( ) method to connect to a specified SocketAddress. The connect( ) method performs the required security checks once and allows future communication with the specified address without the overhead. Once a DatagramChannel is connected, you can use the standard read( ) and write( ) methods defined by the ReadableByteChannel, WritableByteChannel, GatheringByteChannel and ScatteringByteChannel interfaces. Like the receive( ...

Get Java in a Nutshell, 5th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.