A Simple Chat System

It’s a pretty simple matter to build a basic chat system on top of our base classes. All we need to do is write a subclass of our collaborator that acts as a chat client, receiving messages from remote chat clients and displaying them in a text window next to their name. We can pull each client’s name from its Identity. Example 10.1 shows an RMIChatClient based on our RMI collaborative system. The RMIChatClient extends the RMICollaboratorImpl class, and also implements the java.awt.event.ActionListener interface, so that it can act as a listener for its own AWT elements. This AWT interface includes a TextArea for showing the chat session, a TextField for the user to type in chat messages, and a Button to submit the messages to the chat server, which in our case is simply one of our RMIMediatorImpl objects routing messages to other RMIChatClients. The constructor for the RMIChatClient simply connects to the specified mediator, then initializes its graphical elements by calling its initGraphics() method. The initGraphics() method creates a Frame, inserts the TextArea, TextField, and Button in the correct locations, then registers itself as an ActionListener for the button. The RMIChatClient’s actionPerformed() method, which is called whenever the “Send” button is pressed, simply gets the text in the TextField when the button is pressed, and broadcasts it to all the other chat clients by calling its broadcast() method with a message tag of “chat.” It then ...

Get Java Distributed Computing now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.