|
Java[tm] Platform Chat Applicationby Allen Lai(May, 2002) We want to hear from you! Please send us your FEEDBACK. The following code sample may contain actual software programs in source code form. This source code is made available for developers to use as needed, pursuant to the terms and conditions of this license.
SECTION A - Short Description/SynopsisSynopsis: This code sample provides a simple Java[tm] platform chat application illustrating the use of the MulticastSocket class with Swing classes to construct the GUI of the chat program.This code sample is a fully functional Java platform chat application program that can be installed and executed on the Java[tm] runtime environment (JRE), versions 1.2 or above. It uses the MulticastSocket class, which is a subclass of the DatagramSocket class provided by the java.net package. Being a subclass of the DatagramSocket class, the MulticastSocket class is a UDP based DatagramSocket that is useful to programmers who are interested in sending and receiving IP-based multicast packets over a network. It also provides the ability for the application to join a group of multicast hosts on the network. A multicast group of hosts is a group with a Class D IP address range from 224.0.0.1 to 239.255.255.255, and is over a specified standard UDP socket port number. This chat program sends and receives string messages over a selected multicast address of "228.5.6.7", and a UDP port number of 4321. The main thread does the sending of the string text messages while a secondary thread is created to receive the messages. The reader (an inner class that extends Thread) just loops forever. Once it receives a packet on the wire, it extracts the string message and displays it onto the text area of this application's graphical user interface (GUI). The GUI that the user is presented with is constructed using a JFrame with Border layout. The MultiChat main constructor draws the display area (a JTextArea) and a text input field (a JTextField) for the user to key in the message text placed in the center of the frame. IMPORTANT NOTE:
SECTION B - Task and Skeleton CodeI. Task list1. Starting with the skeleton code, first import the relevant packages, namely the java.net and javax.swing packages.The program extends JPanel and adds the ActionListener interface for the purpose of exiting the program when the GUI window is closed. 2. Create a send() method whose function is to grab the text strings for the user input and send them out to a socket as datagram packets in byte form. 3. Create an inner class that extends Thread. The function of this inner class is to implement a run() method to read the datagram packet that is sent to the selected mutlicast address and port number respectively. Once a datagram packet is received, this reader thread will extract the string text message and append it to the text area display of the GUI. 4. Create the main constructor for this program. Select a multicast address as a the multicast group to use and create a MulticastSocket bound to the port number of choice. Grab the network interface IP address and use the joinGroup() method for joining the multicast group. 5. Still referencing the main constructor, create the GUI using Swing. Set the GUI to the cross platform look and feel using the Border layout with two components to be added to the center of the layout for 1) the text messages display, and 2) user text strings input by the sender. The area to display the messages that is sent over the multicast socket uses a JTextArea component while the sender's text message input uses a JTextField component. The reader thread is then started within this main constructor. 6. Next, create an actionPerformed() method to handle the events when a RETURN is hit after the sender has finished with the text of a message. This method calls the send() method created at the top of the source code to send the text string message. If the string text matches the word "quit", then the program terminates and exits. 7. Lastly, use the main() method to construct a JFrame that has the frame constructed in the main constructor placed in the center, and a text label at the bottom to inform the sender that if the word "quit" is typed into the text field, the program exits. II. Skeleton Code//import statementsimport java.net.* ; import java.io.* ; import javax.swing.*; import java.awt.*; import java.util.Calendar; public class MultiChat extends JPanel implements ActionListener { // variable declarations private void send(String msg) throws IOException { // Get an instance of the current date/time. // Create a string buffer to contain the current timestamp, the user id and message strings // Create an array of bytes from the string buffer // Convert the array of bytes to a datagram packet and send it out to the opened socket connection class Reader extends Thread { // Create the implementation for the run() method. // Instantiate an array of 512 byte elements and a datagram packet object set to null.
// Using a while loop, using the receive() method of the MulticastSocket,
listen for any packet that may be sent for a hosts within
// If a packet is detected, extract the string text and append it to the text area to display the message. } MultiChat(String name) {
// Create an internet socket address of a multicast address and port number
of choice. Use the default network interface that is on the local host
// Create the GUI for this chat application. Use the setLookAndFeel()
from the UIManager class to force the swing components to come up
// Use the Border layout for the GUI. Create an area where the text string
messages will be seen when a RETURN is hit. This is done with a
// Start the Reader thread } public void actionPerformed(ActionEvent evt) {
// Check the text in the text field area. Test the text and if it matches
the word "Quit" ignoring the case, then exit the program. Otherwise call
the
// Finally, clear the text field. } protected static final class AppCloser extends WindowAdapter { // Implement the windowClosing() method to exit the program when the window is closed by the user } public static void main(String[] args) {
// Set the id of the chat user to "Anonymous" if there is no argument provided
when the program is run from the command line. Otherwise, take the
// Create a JFrame with Border layout and add the MultiChat GUI
onto the center. Use a JLabel and indicate to the user how to
quit/exit the application
// Add the window listener with AppCloser() to this frame. // Size the frame appropriately and display the JFrame. }
SECTION C - Solution Sourceimport java.net.*;import java.io.*; import javax.swing.*; import java.awt.event.*; import java.awt.*; import java.util.Calendar; /*
public class MultiChat extends JPanel implements ActionListener { JTextArea textarea = null;
/**
/**
/**
super(true);
// This is the multicast
group we'll be using.
try {
// get the default Network Interface
// From here onwards, the GUI is created // Force SwingSet to
come up in the Cross Platform L&F
setBorder(BorderFactory.createEtchedBorder());
// Create the area in
which the messages will be seen after a RETURN is hit.
// Create the area in
which the user can key in the text message to be displayed.
add("Center", scrollpane);
textfield.addActionListener(this);
// When the user hits <RETURN> this method
is called
// So you want to quit?
// OK, let's just send the message then
// And clear the TextField
} catch (IOException e) { e.printStackTrace(); } } /**
protected static final class AppCloser extends WindowAdapter { public void windowClosing(WindowEvent
e) {
} /**
public static void main(String[] args) { String name = "Anonymous";
// Add the comps...
} } Doc ID #824 | |||||||||||||||||||||||||||||||||||||||