These examples show you how to change a simple socket class, named simpleSocketClient, so that it uses socket factories to create all of the sockets. The first example shows you the simpleSocketClient class without socket factories. The second example shows you the simpleSocketClient class with socket factories. In the second example, simpleSocketClient is renamed to factorySocketClient.
Example 1: Socket client program without socket factories
/* Simple Socket Client Program */ import java.net.*; import java.io.*; public class simpleSocketClient { public static void main (String args[]) throws IOException { int serverPort = 3000; if (args.length < 1) { System.out.println("java simpleSocketClient 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); // Create the socket and connect to the server. Socket s = new Socket(args[0], serverPort); . . . // The rest of the program continues on from here.
Example 2: Simple socket client program with socket factories
/* Simple Socket Factory Client Program */ // Notice that javax.net.* is imported to pick up the SocketFactory class. 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); // Change the original simpleSocketClient program to create a // SocketFactory and then use the socket factory to create sockets. SocketFactory socketFactory = SocketFactory.getDefault(); // Now the factory creates the socket. This is the last change // to the original simpleSocketClient program. 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 socket factories.