Java Reference
In-Depth Information
Table 12-1. Socket options supported by datagram sockets
Option
Type
Constant
Purpose
SO_SNDBUF
Size of the buffer used for
sending datagram packets
StandardSocketOptions.
Integer
SO_RCVBUF
Size of the buffer used for
receiving datagram packets
StandardSocketOp
tions.SO_RCVBUF
Integer
SO_REUSEADDR
Enable/disable address reuse
StandardSocketOptions.SO_RE
USEADDR
Boolean
SO_BROADCAST
Enable/disable broadcast
messages
StandardSocketOp
tions.SO_BROADCAST
Boolean
IP_TOS
Traffic class
StandardSocketOptions.IP_TOS
Integer
IP_MULTICAST_IF
Local network interface to use for
multicast
StandardSocketOptions.IP_MUL
TICAST_IF
NetworkInter
face
IP_MULTICAST_TTL
Time-to-live value for multicast
datagrams
StandardSocketOptions.IP_MUL
TICAST_TTL
Integer
IP_MULTICAST_LOOP StandardSocketOptions.IP_MUL
TICAST_LOOP
Enable/disable loopback of
multicast datagrams
Boolean
The first five options have the same meanings as they do for datagram sockets as de‐
scribed in “Socket Options” on page 417 . The last three are used by multicast sockets,
which we'll take up in Chapter 13 .
These are inspected and configured by just three methods:
public <T> DatagramChannel setOption(SocketOption<T> name, T value)
throws IOException
public <T> T getOption(SocketOption<T> name) throws IOException
public Set<SocketOption<?>> supportedOptions()
The supportedOptions() method lists the available socket options. The getOption()
method tells you the current value of any of these. And setOption() lets you change
the value. For example, suppose you want to send a broadcast message. SO_BROAD‐
CAST is usually turned off by default, but you can switch it on like so:
try (DatagramChannel channel = DatagramChannel.open()) {
channel.setOption(StandardSocketOptions.SO_BROADCAST, true);
// Send the broadcast message...
} catch (IOException ex) {
// handle exceptions...
}
Example 12-18 opens a channel just to check the default values of these options.
Example 12-18. Default socket option values
import java.io.IOException ;
import java.net.SocketOption ;
import java.nio.channels.DatagramChannel ;
 
Search WWH ::




Custom Search