Dr. Dobb's is part of the Informa Tech Division of Informa PLC

This site is operated by a business or businesses owned by Informa PLC and all copyright resides with them. Informa PLC's registered office is 5 Howick Place, London SW1P 1WG. Registered in England and Wales. Number 8860726.


Channels ▼
RSS

.NET

Java, JFactory, and Network Development


September 1996: Java, JFactory and Network Development

Java, JFactory, and Network Development

Visual development meets client/server

Eldon Metz

Eldon, a developer for Rogue Wave Software, can be contacted at [email protected].


JFactory is a cross-platform screen painter, prototyper, and code generator for Java that lets you concentrate on the design and functionality of your GUI by generating Java's Abstract Window Toolkit (AWT) source code. As a developer of JFactory, I'm often asked how it can be used to build client/server applications. To answer this question, I'll describe the development of a chat application called "JChat"-an Internet-based client/server Java application that uses sockets for communication.

The project file, source code, and API documentation for the application are available electronically or at URL http://www.roguewave .com by following the links to the JChat sample page. You may find the classes packaged in COM.roguewave.jchat useful. They are freely modifiable and distributable. The javadoc-generated API documentation and full source code for the foundation objects that comprise the client and server can also be found at URL http:// www.roguewave.com.

JChat Specifications

The JChat server is an asynchronous, multithreaded Java application. The server keeps track of an unlimited number of connections (abstract representations of the socket-pair relationship between a client and server) and forums (any number of connections on a topic of interest). Connection requests from clients are continuously accepted. Once a successful connection has been established, the client sends the name of its user to the server. The server adds the connection to its collection of current connections, and sends to the client the names of all the forums that are currently available to join.

Once a connection is established, each client communicates with the server by sending commands. Each client has a connection that monitors a particular socket for incoming data. As soon as a complete command is received, the command is processed and the appropriate action is performed.

The JChat client, on the other hand, is Internet based and can be executed as an applet running within a Java-enabled web browser. The asynchronous, multithreaded JChat client consists of a GUI that allows users to connect to the server, join and contribute to existing forums, and create new forums.

Creating the JChat Server

The server is a stand-alone Java application that creates a Receptionist and Dispatcher. It is started by running the Java interpreter on the Server class (that is, java Server). It runs continuously (Ctrl-C will stop it). The Receptionist listens for incoming connection requests, then hands them to a dispatcher, which takes care of processing the commands that are received from each client. The Dispatcher is an abstract class and both the server and client instantiate a specialized implementation of it. The server implements a ForumDispatcher to process commands from clients, which are made up of four strings. Table 1(a) lists the commands the ForumDispatcher object understands. The client implements a ForumViewDispatcher to process commands received from the server. Table 1(b) lists commands understood by the ForumViewDispatcher object.

Creating the JChat Client

I used JFactory to design, prototype, and generate most of the code for the JChat client. Overall, it took less than an hour to build the graphical part of JChat (including the time required to change or add to the design). Consequently, I won't go into a blow-by-blow description of how you create the JChat client. After all, the process largely involves visual drag-and-drop and point-and-click. What I will do, however, is briefly discuss JFactory basics, then identify the fundamental steps involved in designing and implementing JChat.

Creating a new project in JFactory is straightforward. A single dialog prompts you for the name, directory, and template project to begin with. The template projects you can choose from are customizable, but JFactory ships with typical Applet, Application, and Menu Application templates. JFactory lets you change the type of code to be generated for the project (application versus applet) at any time by changing the project's Type property. Be careful, however, as security restrictions differ. (For example, a Java application can write to a local disk, but an applet cannot.)

Once a new project is created, the Project Manager, Object Manager, and Tool Palette windows arrange themselves on screen (see Figure 1). If you don't like the default window arrangement, JFactory allows you to choose three others. If your workspace gets cluttered, a menu-item selection will reorganize to the layout you have specified. The Project Manager lets you view, add, and modify every control in the project in a hierarchical way. The Object Manager consists of tabbed sheets that list the properties and events for every object that can be changed or handled from within the JFactory interface. Selecting an object in the Project Manager will instruct the Object Manager to display the current property and event settings for it.

There are five steps required to build an application such as JChat:

    1.Design the Main window (see Figure 2). You use the Window Designer to do this.

      2.Design the connection-error dialog. This will cause an error message like Figure 3 to pop up when an error occurs during connection to the server.

        3.Design the forum-list window (Figure 4) and new forum dialog.

          4.Design the forum-view window: the window in the JChat GUI that lets users view and add to the discussion taking place in a particular forum.

            5.Test the prototype (Figure 5) by selecting the Test app button on the JFactory toolbar.

          Adding User-Defined Code

          Once you've tested the GUI for functionality, you can begin adding the code that will be used to make the connection with the JChat server. JFactory provides protect blocks that prevent user code from being deleted across subsequent code regeneration.

          Before adding any Java source code, look at the code JFactory generates for handling the event when the Connect button is pressed. Pressing the Generate button on the JFactory toolbar, then browsing the code to find the action method for the Main window results in Listing One. Notice that there are two sets of protect blocks, one to allow user-defined code to be entered before the window is shown and another for after the window is shown. For this particular case, we want to add user-defined code before the window is shown. If the connection with the server fails, a return from the event handler with a True value will complete the event-handler chain of events for the button hierarchy.

          Right after the MainConnectbuttonClickedShow protect block, Socket, Connection, and ForumViewDispatcher objects are declared. The Connection object encapsulates the client/server communication details. The ForumViewDispatcher object encapsulates the details of how the commands are processed as they come over the socket, and which TextArea will be updated. A try-catch block around the Socket instantiation is where an Exception can be thrown if the connection fails. For JChat, a server port number of 6600 was hardwired into the source code. If an Exception is caught, the ErrorDialog is declared, instantiated, and shown before control leaves the event handler.

          If the socket connection with the server succeeds, the Connect button is disabled and a Connection object is instantiated. The Connection object is used by both the client and the server. To specify that the newly instantiated Connection object is the Client, the user name entered into the UserName Edit control must be passed to the setClient() method. The Connection is then handed to the Dispatcher, and the listbox in ForumListWindow is added as an object to notify when a new forum is created. The references of these newly created Connection and ForumViewDispatcher objects are passed to the newly created ForumListWindow object. To do this, two public data members are added to the ForumListWindow object.

          Each class generated by JFactory has protect blocks for user-defined methods and data members. The code for the Connection and Dispatcher data members is shown in Listing Two, and the event-handler code for the Connect button now looks like Listing Three.

          Now is a good time to ensure that the code that has been written is correct. Before compiling the code, the packages and classes being used need to be imported. With JFactory, this is done by selecting the project icon in the Project Manager and then modifying the ImportFiles property in the Object Manager. Add COM .roguewave.jchat.* and java.net.Socket to the list. It is important to verify that the CLASSPATH environment variable points to the base of the COM.roguewave.jchat package.

          Pressing the Generate & Make button on the JFactory toolbar generates and compiles the Java source code with the modifications in the protect blocks.

          Since the JChat client is an applet, JFactory also generates an HTML file that is viewable with appletviewer or any other Java-enabled browser. To test the client, the JChat server must first be running on the same machine that the Client is served from. Pressing the Run App button on the JFactory toolbar will display the JChat main window in appletviewer (the default HTML viewer). Pressing the Connect button will display the ForumListWindow. So far, JFactory has helped design the entire GUI and has required less than 20 lines of user-defined Java source code to connect to the server.

          ForumListWindow needs to keep track of all the forums that are currently being viewed by the user. ForumListWindow also needs to handle the events for the ForumList, Join Forum, and New Forum, and Close Connection buttons. Furthermore, any time users destroy ForumListWindow, the connection with the server should be safely terminated.

          To keep track of all the forums that are currently being viewed by the user, a data member can be added to the ForumListWindow object. A Vector can be used as the collection object, and this will have to be instantiated in the constructor. To add the code for the Vector instantiation in JFactory, SourceCode is chosen for the constructor event in the Object Manager's Events sheet for the ForumListWindow. Listing Four shows the user-defined code that needed to be added to the JFactory-generated source code. The Join Forum button is initially disabled. When the user selects a forum in the ForumList, it should be enabled. To enable the Join Forum button, the line pJoinButton,enable(), had to be added as SourceCode to the selection event for ForumList; see Listing Five. When the deselect event occurs, the Join Forum button should be disabled. Listing Six presents the code that needs to be added.

          Another event that is important to handle is the destroy event for the ForumListWindow. Both the Close Connection button and this event should safely close the connection. A cleanup() call was added, since the same method is used when the Close-button-clicked event occurs. Listing Seven is the code for all these changes.

          When the user clicks on the New Forum button, the Connection instance must be passed to the Dialog object. This is done by declaring a data member that is publicly accessible. Listing Eight is the code for passing the reference.

          When the Join Forum button is clicked, the forum that is to be joined needs to be added to the vector of forum views. The title of the window will be modified so that the user can distinguish which forum a particular instance of ForumViewWindow is viewing. The ForumArea object in the ForumViewWindow needs to be added to the dispatcher. When a message posted to that particular forum arrives, the dispatcher will then be able to update the ForumArea object with the message. A command needs to be sent to the JChat server informing it that another user has connected to a particular forum. Listing Nine is the Java source code to implement these details.

          Attaching Functionality to the NewForumDialog

          A Connection data member needs to be added to the NewForumDialog object, so the ForumListWindow can reference it when the OK-button-clicked event occurs. The code for adding the Connection data member is shown in Listing Ten. When the OK button is pressed, the server should receive a create-new-forum command. Listing Eleven is the code to be added. The JChat server will parse the command, create a new Forum object, and notify all the existing connections of the new forum that needs to be added to their list.

          Pressing the Make button on the JFactory toolbar compiles the Java source code with all the modifications that have been made in protect blocks. There is no need to regenerate the source code, since the GUI has not been modified. The JChat client can now connect to the server and add new forums to the list of forums in the ForumListWindow. The disabling and enabling of the Join Forum button can now be tested to ensure it is working as it should. Destroying the window or pressing the Close Connection button should safely close the socket connection and re-enable the Connect button in the Main window. A forum is joinable but the functionality to post messages to one has not been added.

          Attaching functionality to the ForumViewWindow

          The ForumViewWindow appears when the Join Forum button is clicked. The ForumViewWindow object will need two data members, one for the connection, and one that represents the forum name that is being viewed. Listing Twelve is code for adding these data members

          There are three events that must be handled in the ForumViewWindow. The Options/Exit menu item should close ForumViewWindow and inform the server that this connection is no longer viewing this particular forum. The WINDOW_DESTROY event should also be handled, and it should do the same thing as Options/Exit.

          To handle the Options/Exit event, the Window Designer for the ForumViewWindow can be opened by double-clicking on it in the Project Manager. Selecting the Options/Exit menu item and then choosing SourceCode for the selection event in the Events sheet in the Object Manger will bring up the source-code editor with the cursor right at the place where the code was entered; see Listing Thirteen. To handle the WINDOW_DESTROY event in the same way, I added Listing Fourteen.

          The last event that needs to be handled is the Post-button-clicked event. This event informs the server that a new message has been posted to a particular forum. Listing Fifteen is the source code for this event.

          At this point, the JChat client is fully functional. Pressing the Make button from the JFactory toolbar compiles the rest of the changes to the bytecode.

          Technical Issues and Solutions

          Netscape will only allow a Java applet to connect to a server that is running on the same machine that the client is served from. I had originally planned to let users choose which port and server they wished to connect to. This adds complexity, and Netscape's limitations actually made the Main window of the JChat client more user friendly. However, this forces the Java server to be running on the HTTP server, which in some environments may not be reasonable.

          Due to this security restriction mandated by Netscape 2.0, the JChat user is not required to enter the address of the server they wish to connect to. It is possible to get the full hostname of the HTTP server that the applet was served from with the line of code applet.getCodeBase().getHost(). The object applet must be an instance of Applet or an object that extends (or subclasses) Applet.

          Summary

          JFactory makes it possible for you to rapidly prototype and design GUIs via drag-and-drop, point-and-click interfaces. Source code to handle events can then be added to the generated GUI code between protect blocks via the Events sheet in the Object Manager. After functionality has been attached in the form of user-added Java source code, the controls can be moved around without changing any source code that you've written to add functionality. The most time-consuming part in creating JChat was writing the Java source code to enable the client to communicate properly with the server.

          Table 1: (a) Commands the ForumDispatcher object understands; (b) commands understood by the ForumViewDispatcher object.

          (a)
          
          attach "forumname" "username" ""
          detach "forumname" "username" ""
          create "forumname" "username" ""
          post   "forumname" "username" "message"
          close  ""         "username" ""
          
          (b)
          
          post "forumname" "username" "message"
          add  "forumname" ""         ""
          

          Figure 1: JFactory desktop.

          Figure 2: JChat main window.

          Figure 3: Error dialog.

          Figure 4: The forum list window.

          Figure 5: Testing the JChat GUI.

          For More Information

          Rogue Wave Software

          850 SW 35th Street

          Corvallis, OR 97333

          800-487-3217

          http://www.roguewave.com


          Related Reading


          More Insights






          Currently we allow the following HTML tags in comments:

          Single tags

          These tags can be used alone and don't need an ending tag.

          <br> Defines a single line break

          <hr> Defines a horizontal line

          Matching tags

          These require an ending tag - e.g. <i>italic text</i>

          <a> Defines an anchor

          <b> Defines bold text

          <big> Defines big text

          <blockquote> Defines a long quotation

          <caption> Defines a table caption

          <cite> Defines a citation

          <code> Defines computer code text

          <em> Defines emphasized text

          <fieldset> Defines a border around elements in a form

          <h1> This is heading 1

          <h2> This is heading 2

          <h3> This is heading 3

          <h4> This is heading 4

          <h5> This is heading 5

          <h6> This is heading 6

          <i> Defines italic text

          <p> Defines a paragraph

          <pre> Defines preformatted text

          <q> Defines a short quotation

          <samp> Defines sample computer code text

          <small> Defines small text

          <span> Defines a section in a document

          <s> Defines strikethrough text

          <strike> Defines strikethrough text

          <strong> Defines strong text

          <sub> Defines subscripted text

          <sup> Defines superscripted text

          <u> Defines underlined text

          Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

           
          Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.