Thursday, March 16, 2017

Java Chat Application, Class Chat Client Creation

Creating a chat application using java, creating class Chat Client

Class ChatClient

This class implements the chat client, as described. This involves setting up a basic user interface, handling user interaction, and receiving messages from the server.
import java.net.*;
import java.io.*;
import java.awt.*;
public class ChatClient extends Frame implements Runnable {
  // public ChatClient (String title, InputStream i, OutputStream o) ...
  // public void run () ...
  // public boolean handleEvent (Event e) ...
  // public static void main (String args[]) throws IOException ...
}
The ChatClient class extends Frame; this is typical for a graphical application. We implement the Runnable interface so that we can start a Thread that receives messages from the server. The constructor performs the basic setup of the GUI, the run() method receives messages from the server, the handleEvent()method handles user interaction, and the main() method performs the initial network connection.
  protected DataInputStream i;
  protected DataOutputStream o;
  protected TextArea output;
  protected TextField input;
  protected Thread listener;
  public ChatClient (String title, InputStream i, OutputStream o) {
    super (title);
    this.i = new DataInputStream (new BufferedInputStream (i));
    this.o = new DataOutputStream (new BufferedOutputStream (o));
    setLayout (new BorderLayout ());
    add ("Center", output = new TextArea ());
    output.setEditable (false);
    add ("South", input = new TextField ());
    pack ();
    show ();
    input.requestFocus ();
    listener = new Thread (this);
    listener.start ();
  }
public void run () {
    try {
      while (true) {
        String line = i.readUTF ();
        output.appendText (line + "\n");
      }
    } catch (IOException ex) {
      ex.printStackTrace ();
    } finally {
      listener = null;
      input.hide ();
      validate ();
      try {
        o.close ();
      } catch (IOException ex) {
        ex.printStackTrace ();
      }
    }
  }
To clean up, we first assign our listener reference to this Thread to null; this indicates to the rest of the code that the thread has terminated. We then hide the input field and call validate() so that the interface is laid out again, and close the OutputStream o to ensure that the connection is closed.
Note that we perform all of the cleanup in a finally clause, so this will occur whether an IOException occurs here or the thread is forcibly stopped. We don't close the window immediately; the assumption is that the user may want to read the session even after the connection has been lost.
public boolean handleEvent (Event e) {
    if ((e.target == input) && (e.id == Event.ACTION_EVENT)) {
      try {
        o.writeUTF ((String) e.arg);
        o.flush ();
      } catch (IOException ex) {
        ex.printStackTrace();
        listener.stop ();
      }
      input.setText ("");
      return true;
    } else if ((e.target == this) && (e.id == Event.WINDOW_DESTROY)) {
      if (listener != null)
        listener.stop ();
      hide ();
      return true;
    }
    return super.handleEvent (e);
  }
In thehandleEvent() method, we need to check for two significant UI events:
The first is an action event in the TextField, which means that the user has hit the Return key. When we catch this event, we write the message to the output stream, then call flush() to ensure that it is sent immediately. The output stream is a DataOutputStream, so we can use writeUTF() to send a String. If an IOException occurs the connection must have failed, so we stop the listener thread; this will automatically perform all necessary cleanup.
The second event is the user attempting to close the window. It is up to the programmer to take care of this task; we stop the listener thread and hide the Frame.
public static void main (String args[]) throws IOException {
    if (args.length != 2)
      throw new RuntimeException ("Syntax: ChatClient <host> <port>");
    Socket s = new Socket (args[0], Integer.parseInt (args[1]));
    new ChatClient ("Chat " + args[0] + ":" + args[1],
                    s.getInputStream (), s.getOutputStream ());
  }
The main() method starts the client; we ensure that the correct number of arguments have been supplied, we open aSocket to the specified host and port, and we create a ChatClient connected to the socket's streams. Creating the socket may throw an exception that will exit this method and be displayed.

No comments:

Post a Comment

Implemting Google Drive File Uploader using OAuth

Implementing Google Drive Text File Uploader using OAuth 2.0 Creating Project and Registering your API with Google In this part we wil...