Java Reference
In-Depth Information
This constructor can throw an
IOException
or an
UnknownHostException
for the same
reasons as the previous constructors. In addition, it throws an
IOException
(probably
a
BindException
, although again that's just a subclass of
IOException
and not specifi‐
cally declared in the
throws
clause of this method) if the socket is unable to bind to the
requested local network interface. For instance, a program running on
a.example.com
can't connect from
b.example.org
. You could take deliberate advantage of this to restrict
a compiled program to run on only a predetermined host. It would require customizing
distributions for each computer and is certainly overkill for cheap products. Further‐
more, Java programs are so easy to disassemble, decompile, and reverse engineer that
this scheme is far from foolproof. Nonetheless, it might be part of a scheme to enforce
a software license.
Constructing Without Connecting
All the constructors we've talked about so far both create the socket object and open a
network connection to a remote host. Sometimes you want to split those operations. If
you give no arguments to the
Socket
constructor, it has nowhere to connect to:
public
Socket
()
You can connect later by passing a
SocketAddress
to one of the
connect()
methods.
For example:
try
{
Socket
socket
=
new
Socket
();
// fill in socket options
SocketAddress
address
=
new
InetSocketAddress
(
"time.nist.gov"
,
13
);
socket
.
connect
(
address
);
// work with the sockets...
}
catch
(
IOException
ex
)
{
System
.
err
.
println
(
ex
);
}
You can pass an
int
as the second argument to specify the number of milliseconds to
wait before the connection times out:
public
void
connect
(
SocketAddress
endpoint
,
int
timeout
)
throws
IOException
The default, 0, means wait forever.
The raison d'être for this constructor is to enable different kinds of sockets. You also
need to use it to set a socket option that can only be changed before the socket connects.
I'll discuss this in
“Setting Socket Options” on page 259
. However, the prime benefit I find
is that it enables me to clean up the code in
try
-
catch
-
finally
blocks, especially prior
to Java 7. The noargs constructor throws no exceptions so it enables you to avoid the
annoying null check when closing a socket in a
finally
block. With the original con‐
structor, most code looks like this: