Java Reference
In-Depth Information
need here for a finishConnect() or isConnectionPending() method. There is an
isConnected() method that returns true if and only if the DatagramSocket is connec‐
ted:
public boolean isConnected ()
This tells you whether the DatagramChannel is limited to one host. Unlike SocketChan
nel , a DatagramChannel doesn't have to be connected to transmit or receive data.
Finally, the disconnect() method breaks the connection:
public DatagramChannel disconnect () throws IOException
This doesn't really close anything because nothing was really open in the first place. It
just allows the channel to be connected to a different host in the future.
Reading
Besides the special-purpose receive() method, DatagramChannel has the usual three
read() methods:
public int read ( ByteBuffer dst ) throws IOException
public long read ( ByteBuffer [] dsts ) throws IOException
public long read ( ByteBuffer [] dsts , int offset , int length )
throws IOException
However, these methods can only be used on connected channels. That is, before in‐
voking one of these methods, you must invoke connect() to glue the channel to a
particular remote host. This makes them more suitable for use with clients that know
who they'll be talking to than for servers that must accept input from multiple hosts at
the same time that are normally not known prior to the arrival of the first packet.
Each of these three methods only reads a single datagram packet from the network. As
much data from that datagram as possible is stored in the argument ByteBuffer (s).
Each method returns the number of bytes read or -1 if the channel has been closed.
This method may return 0 for any of several reasons, including:
• The channel is nonblocking and no packet was ready.
• A datagram packet contained no data.
• The buffer is full.
As with the receive() method, if the datagram packet has more data than the Byte
Buffer (s) can hold, the extra data is thrown away with no notification of the problem .
You do not receive a BufferOverflowException or anything similar.
Writing
Naturally, DatagramChannel has the three write methods common to all writable, scat‐
tering channels, which can be used instead of the send() method:
Search WWH ::




Custom Search