Java Reference
In-Depth Information
}
}
catch
(
SocketException
ex
)
{
System
.
err
.
println
(
ex
);
}
catch
(
IOException
ex
)
{
System
.
err
.
println
(
"Unexpected IOException: "
+
ex
);
}
The
getSoTimeout()
method returns the current value of this
DatagramSocket
object's
SO_TIMEOUT field. For example:
public
void
printSoTimeout
(
DatagramSocket
ds
)
{
int
timeout
=
ds
.
getSoTimeOut
();
if
(
timeout
>
0
)
{
System
.
out
.
println
(
ds
+
" will time out after "
+
timeout
+
"milliseconds."
);
}
else
if
(
timeout
==
0
)
{
System
.
out
.
println
(
ds
+
" will never time out."
);
}
else
{
System
.
out
.
println
(
"Something is seriously wrong with "
+
ds
);
}
}
SO_RCVBUF
The SO_RCVBUF option of
DatagramSocket
is closely related to the SO_RCVBUF
option of
Socket
. It determines the size of the buffer used for network I/O. Larger buffers
tend to improve performance for reasonably fast (say, Ethernet-speed) connections be‐
cause they can store more incoming datagrams before overflowing. Sufficiently large
receive buffers are even more important for UDP than for TCP, because a UDP datagram
that arrives when the buffer is full will be lost, whereas a TCP datagram that arrives at
a full buffer will eventually be retransmitted. Furthermore, SO_RCVBUF sets the max‐
imum size of datagram packets that can be received by the application. Packets that
won't fit in the receive buffer are silently discarded.
DatagramSocket
has methods to set and get the suggested receive buffer size used for
network input:
public
void
setReceiveBufferSize
(
int
size
)
throws
SocketException
public
int
getReceiveBufferSize
()
throws
SocketException
The
setReceiveBufferSize()
method suggests a number of bytes to use for buffering
input from this socket. However, the underlying implementation is free to ignore this
suggestion. For instance, many 4.3 BSD-derived systems have a maximum receive buffer
size of about 52K and won't let you set a limit higher than this. My Linux box was limited
to 64K. Other systems raise this to about 240K. The details are highly platform-
dependent. Consequently, you may wish to check the actual size of the receive buffer
with
getReceiveBufferSize()
after setting it. The
getReceiveBufferSize()
method
returns the number of bytes in the buffer used for input from this socket.