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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access