29. Menus, Toolbars, Dialogs, and Internal Frames

 
[Page 826 ( continued )]

25.5. Applet Clients

Because of security constraints, applets can only connect to the host from which they were loaded. Therefore, the HTML file must be located on the machine on which the server is running. You can obtain the server's host name by invoking getCodeBase().getHost() on an applet, you can write the applet without the host name fixed. Below is an example of how to use an applet to connect to a server.

The applet shows the number of visits made to a Web page. The count should be stored in a file on the server side. Every time the page is visited or reloaded, the applet sends a request to the server, and the server increases the count and sends it to the applet. The applet then displays the new count in a message, such as You are visitor number 11 , as shown in Figure 25.9. The server and client programs are given in Listings 25.5 and 25.6.


[Page 827]
Figure 25.9. The applet displays the access count on a Web page.


Listing 25.5. CountServer.java
 1   import   java.io.*; 2   import   java.net.*; 3 4   public class   CountServer { 5   private   RandomAccessFile raf; 6   private int   count;  // Count the access to the server  7 8   public static void   main(String[] args) { 9   new   CountServer(); 10 } 11 12   public   CountServer() { 13   try   { 14  // Create a server socket  15  ServerSocket serverSocket =   new   ServerSocket(   8000   );  16 System.out.println(   "Server started "   ); 17 18  // Create or open the count file  19  raf =   new   RandomAccessFile(   "count.dat"   ,   "rw"   );  20 21  // Get the count  22   if   (raf.length() ==     ) 23  count =     ;  24   else   25  count = raf.readInt();  26 27   while   (   true   ) { 28  // Listen for a new connection request  29  Socket socket = serverSocket.accept();  30 31  // Create a DataOutputStream for the socket  32  DataOutputStream outputToClient =  33    new   DataOutputStream(socket.getOutputStream());  34 35  // Increase count and send the count to the client  36  count++;  37  outputToClient.writeInt(count);  38 39  // Write new count back to the file  40  raf.seek(     );  41  raf.writeInt(count);  42 } 43 } 44   catch   (IOException ex) { 45 ex.printStackTrace(); 46 } 47 } 48 } 


[Page 828]

The server creates a ServerSocket in line 15 and creates or opens a file using RandomAccessFile in line 19. It reads the count from the file in lines 22 “25. The server then waits for a connection request from a client (line 29). After a connection with a client is established, the server creates an output stream to the client (lines 32 “33), increases the count (line 36), sends the count to the client (line 37), and writes the new count back to the file. This process continues in an infinite while loop to handle all clients.

Listing 25.6. AppletClient.java
(This item is displayed on pages 828 - 829 in the print version)
 1   import   java.io.*; 2   import   java.net.*; 3   import   java.awt.BorderLayout; 4   import   javax.swing.*; 5 6   public class   AppletClient   extends   JApplet { 7  // Label for displaying the visit count  8   private   JLabel jlblCount =   new   JLabel(); 9 10  // Indicate if it runs as application  11    private boolean   isStandAlone =   false   ;  12 13  // Host name or ip  14   private   String host =   "localhost"   ; 15 16  /** Initialize the applet */  17   public void   init() { 18 add(jlblCount); 19 20   try   { 21  // Create a socket to connect to the server  22 Socket socket; 23   if   (isStandAlone) 24  socket =   new   Socket(host,   8000   );  25   else   26  socket =   new   Socket(getCodeBase().getHost(),   8000   );  27 28  // Create an input stream to receive data from the server  29  DataInputStream inputFromServer =  30    new   DataInputStream(socket.getInputStream());  31 32  // Receive the count from the server and display it on label  33    int   count = inputFromServer.readInt();  34 jlblCount.setText(   "You are visitor number "   + count); 35 36  // Close the stream  37 inputFromServer.close(); 38 } 39   catch   (IOException ex) { 40 ex.printStackTrace(); 41 } 42 } 43 } 44  /** Run the applet as an application */  45   public static void   main(String[] args) { 46  // Create a frame  47 JFrame frame =   new   JFrame(   "Applet client"   ); 48 49  // Create an instance of the applet  50 AppletClient applet =   new   AppletClient(); 51 applet.isStandAlone =   true   ; 

[Page 829]
 52 53  // Get host  54   if   (args.length ==   1   ) applet.host = args[     ]; 55 56  // Add the applet instance to the frame  57 frame.getContentPane().add(applet, BorderLayout.CENTER); 58 59  // Invoke init() and start()  60 applet.init(); 61 applet.start(); 62 63  // Display the frame  64 frame.pack(); 65 frame.setVisible(   true   ); 66 } 67 } 

The client is an applet. When it runs as an applet, it uses getCodeBase().getHost() (line 26) to return the IP address for the server. When it runs as an application, it passes the URL from the command line (line 54). If the URL is not passed from the command line, by default "localhost" is used for the URL (line 14).

The client creates a socket to connect to the server (lines 23 “26), creates an input stream from the socket (lines 29 “30), receives the count from the server (line 33), and displays it in the text field (line 34).

 


Introduction to Java Programming-Comprehensive Version
Introduction to Java Programming-Comprehensive Version (6th Edition)
ISBN: B000ONFLUM
EAN: N/A
Year: 2004
Pages: 503

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net