Java Reference
In-Depth Information
Constructing and Connecting Sockets
The
java.net.Socket
class is Java's fundamental class for performing client-side TCP
operations. Other client-oriented classes that make TCP network connections such as
URL
,
URLConnection
,
Applet
, and
JEditorPane
all ultimately end up invoking the
methods of this class. This class itself uses native code to communicate with the local
TCP stack of the host operating system.
Basic Constructors
Each
Socket
constructor specifies the host and the port to connect to. Hosts may be
specified as an
InetAddress
or a
String
. Remote ports are specified as
int
values from
1 to 65535:
public
Socket
(
String
host
,
int
port
)
throws
UnknownHostException
,
IOException
public
Socket
(
InetAddress
host
,
int
port
)
throws
IOException
These constructors connect the socket (i.e., before the constructor returns, an active
network connection is established to the remote host). If the connection can't be opened
for some reason, the constructor throws an
IOException
or an
UnknownHostExcep
tion
. For example:
try
{
Socket
toOReilly
=
new
Socket
(
"www.oreilly.com"
,
80
);
// send and receive data...
}
catch
(
UnknownHostException
ex
)
{
System
.
err
.
println
(
ex
);
}
catch
(
IOException
ex
)
{
System
.
err
.
println
(
ex
);
}
In this constructor, the
host
argument is just a hostname expressed as a
String
. If the
domain name server cannot resolve the hostname or is not functioning, the constructor
throws an
UnknownHostException
. If the socket cannot be opened for some other rea‐
son, the constructor throws an
IOException
. There are many reasons a connection
attempt might fail: the host you're trying to reach may not accept connections on that
port, the hotel WiFi service may be blocking you until you log in to its website and pay
$14.95, or routing problems may be preventing your packets from reaching their des‐
tination.
Because this constructor doesn't just create a
Socket
object but also tries to connect the
socket to the remote host, you can use the object to determine whether connections to
a particular port are allowed, as in
Example 8-5
.