Java Reference
In-Depth Information
Socket
socket
=
null
;
try
{
socket
=
new
Socket
(
SERVER
,
PORT
);
// work with the socket...
}
catch
(
IOException
ex
)
{
System
.
err
.
println
(
ex
);
}
finally
{
if
(
socket
!=
null
)
{
try
{
socket
.
close
();
}
catch
(
IOException
ex
)
{
// ignore
}
}
}
With the noargs constructor, it looks like this:
Socket
socket
=
new
Socket
();
SocketAddress
address
=
new
InetSocketAddress
(
SERVER
,
PORT
);
try
{
socket
.
connect
(
address
);
// work with the socket...
}
catch
(
IOException
ex
)
{
System
.
err
.
println
(
ex
);
}
finally
{
try
{
socket
.
close
();
}
catch
(
IOException
ex
)
{
// ignore
}
}
That's not quite as nice as the autoclosing version in Java 7, but it is an improvement.
Socket Addresses
The
SocketAddress
class represents a connection endpoint. It is an empty abstract class
with no methods aside from a default constructor. At least theoretically, the
SocketAddress
class can be used for both TCP and non-TCP sockets. In practice, only
TCP/IP sockets are currently supported and the socket addresses you actually use are
all instances of
InetSocketAddress
.
The primary purpose of the
SocketAddress
class is to provide a convenient store for
transient socket connection information such as the IP address and port that can be
reused to create new sockets, even after the original socket is disconnected and garbage
collected. To this end, the
Socket
class offers two methods that return
SocketAddress
objects (
getRemoteSocketAddress()
returns the address of the system being connected
to and
getLocalSocketAddress()
returns the address from which the connection is
made):