Java Reference
In-Depth Information
javax.net
The abstract socket factory classes used instead of constructors to create secure
sockets.
java.security.cert
The classes for handling the public-key certificates needed for SSL.
com.sun.net.ssl
The concrete classes that implement the encryption algorithms and protocols in
Sun's reference implementation of the JSSE. Technically, these are not part of the
JSSE standard. Other implementers may replace this package with one of their own;
for instance, one that uses native code to speed up the CPU-intensive key generation
and encryption process.
Creating Secure Client Sockets
If you don't care very much about the underlying details, using an encrypted SSL socket
to talk to an existing secure server is truly straightforward. Rather than constructing a
java.net.Socket
object with a constructor, you get one from a
jav
ax.net.ssl.SSLSocketFactory
using its
createSocket()
method.
SSLSocketFacto
ry
is an abstract class that follows the abstract factory design pattern. You get an instance
of it by invoking the static
SSLSocketFactory.getDefault()
method:
SocketFactory
factory
=
SSLSocketFactory
.
getDefault
();
Socket
socket
=
factory
.
createSocket
(
"login.ibiblio.org"
,
7000
);
This either returns an instance of
SSLSocketFactory
or throws an
InstantiationEx
ception
if no concrete subclass can be found. Once you have a reference to the factory,
use one of these five overloaded
createSocket()
methods to build an
SSLSocket
:
public
abstract
Socket
createSocket
(
String
host
,
int
port
)
throws
IOException
,
UnknownHostException
public
abstract
Socket
createSocket
(
InetAddress
host
,
int
port
)
throws
IOException
public
abstract
Socket
createSocket
(
String
host
,
int
port
,
InetAddress
interface
,
int
localPort
)
throws
IOException
,
UnknownHostException
public
abstract
Socket
createSocket
(
InetAddress
host
,
int
port
,
InetAddress
interface
,
int
localPort
)
throws
IOException
,
UnknownHostException
public
abstract
Socket
createSocket
(
Socket
proxy
,
String
host
,
int
port
,
boolean
autoClose
)
throws
IOException
The first two methods create and return a socket that's connected to the specified host
and port or throw an
IOException
if they can't connect. The third and fourth methods
connect and return a socket that's connected to the specified host and port from the
specified local network interface and port. The last
createSocket()
method, however,