These examples show you how to change one class, named factorySocketClient, to use secure sockets layer (SSL). The first example shows you the factorySocketClient class not using SSL. The second example shows you the same class, renamed factorySSLSocketClient, using SSL.
Example 1: Simple factorySocketClient class without SSL support
/* Simple Socket Factory Client Program */ import javax.net.*; import java.net.*; import java.io.*; public class factorySocketClient { public static void main (String args[]) throws IOException { int serverPort = 3000; if (args.length < 1) { System.out.println("java factorySocketClient serverHost serverPort"); System.out.println("serverPort defaults to 3000 if not specified."); return; } if (args.length == 2) serverPort = new Integer(args[1]).intValue(); System.out.println("Connecting to host " + args[0] + " at port " + serverPort); SocketFactory socketFactory = SocketFactory.getDefault(); Socket s = socketFactory.createSocket(args[0], serverPort); . . . // The rest of the program continues on from here.
Example 2: Simple factorySocketClient class with SSL support
// Notice that we import javax.net.ssl.* to pick up SSL support import javax.net.ssl.*; import javax.net.*; import java.net.*; import java.io.*; public class factorySSLSocketClient { public static void main (String args[]) throws IOException { int serverPort = 3000; if (args.length < 1) { System.out.println("java factorySSLSocketClient serverHost serverPort"); System.out.println("serverPort defaults to 3000 if not specified."); return; } if (args.length == 2) serverPort = new Integer(args[1]).intValue(); System.out.println("Connecting to host " + args[0] + " at port " + serverPort); // Change this to create an SSLSocketFactory instead of a SocketFactory. SocketFactory socketFactory = SSLSocketFactory.getDefault(); // We do not need to change anything else. // That's the beauty of using factories! Socket s = socketFactory.createSocket(args[0], serverPort); . . . // The rest of the program continues on from here.
For background information, see Change your Java™ code to use secure sockets layer.