?
Solved

UI for chat

Posted on 2005-04-10
22
Medium Priority
?
389 Views
Last Modified: 2010-03-31
I've sort of been able to create a UI for a chat client, just don't know how to hook the two together..

package ui;
import java.awt.*;
class UserInterface extends Frame {

      TextArea strTextArea = new TextArea();
      Button btnSubmit = new Button( "Send" );

      UserInterface()
      {
            super( "PacificFox Chat" );
            add( "Center", strTextArea );
            add( "South", btnSubmit );
            pack();
            show();
      }

      public boolean action( Event evt, Object ob )
      {
            if ( evt.target == btnSubmit )
            {
                  String message = strTextArea.getText();
            }
            return true;
      }

      static public void main( String[] args)
      {
            new UserInterface();
      }
}

******************
message is the variable I need to pass to the following class
******************

package v1;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;

//Start: ChatClient Class
public class ChatClient extends Thread
{

      protected Socket incoming;
      protected int id;
      protected BufferedReader in;
      protected PrintWriter out;
      // Constant defining the maximum message length
      final int MAX_MESSAGE_LENGTH = 100;
 

      // Start: Constructor
      public ChatClient( Socket incoming, int id )
      {
            this.incoming = incoming;
            this.id = id;
            try
            {
                  if ( incoming != null )
                  {
                        in = new BufferedReader( new InputStreamReader( incoming.getInputStream() ) );           
                        out = new PrintWriter( new OutputStreamWriter( incoming.getOutputStream() ) );
                  }
            }
            catch (Exception e)
            {
                  System.out.println( "Error: " + e );
            }
      }// End: Constructor


      // Start: putMessage Locked Method
      public synchronized void putMessage( String message )
      {
            // if out is not null then print the message and flush
            if ( out != null )
            {
                  out.println( message );
                  out.flush();
            }
      }// End: putMessage Locked Method

      
      public boolean doValidate( String message )
      {

            // Cannot send empty message
            if ( message.trim().length() == 0  )
            {
                  putMessage( "the message cannot be empty" );
                  return false;
            }
            
            // Cannot send messages greater than the defined length
            if ( message.length() > MAX_MESSAGE_LENGTH )
            {
                  putMessage( "The message cannot be greater than " + MAX_MESSAGE_LENGTH + " characters." );
                  return false;
            }

            return true;
      
      }
      

      // Start: run method of the thread, called by start()
      public void run()
      {
            System.out.println( "Chat Client " + id + " started." );
            if ( in != null && out != null )
            {
                  putMessage( ChatServer.SERVER_NAME + " Chat Server. Enter BYE to exit." );
                  try
                  {
                        while ( true )
                        {
                              String message = in.readLine();
                              // Break out of this iteration if nothing has been passed
                              if ( message == null )
                              {
                                    break;
                              }
                              // If a string has been passed
                              else
                              {
                                    if ( message.trim().equals( "BYE" ) )
                                    {
                                          // Break out of the loop and close this thread
                                          break;
                                    }
                                    boolean shouldBroadcast = doValidate( message );
                                    if ( shouldBroadcast )
                                    {
                                          //putMessage( "Echo: " + message );
                                          // output on server
                                          System.out.println( "Received (" + id + "): " + message );
                                          // Broadcast to all clients
                                          ChatServer.doBroadCast( id, message );
                                    }
                              }
                        }
                        // close this thread
                        incoming.close();
                        // Remove the element from the thread collection
                        ChatServer.activeThreadCollection.removeElement( this );
                  }
                  catch ( IOException e ) {}
            }
            System.out.println( "Chat Client " + id + " stopped." );
      }
}//End: ChatClient Class

**********
Am I doing this right?
0
Comment
Question by:Tacobell777
  • 10
  • 9
  • 2
21 Comments
 
LVL 92

Accepted Solution

by:
objects earned 1000 total points
ID: 13750614
Create an instance of your ChatClient in your main() and pass it to you UI class constructor.
The UI can then store a reference to the ChatClient and call it when it needs to send a message
0
 
LVL 17

Author Comment

by:Tacobell777
ID: 13750764
I dont think that I can do that..

The ChatServer spawns off new instances of the ChatClient.

The code:

package v1;

import java.util.*;
import java.io.*;
import java.net.*;

// Start: ChatServer Class
public class ChatServer
{

      // Global variable
      static protected java.util.Vector activeThreadCollection;
      static protected final String SERVER_NAME = "PacificFox";  


      // Entry point for the java application
      public static void main( String[] args )
      {
            // Notify the user of start of chat server
            java.lang.System.out.println( SERVER_NAME + " Chat Server started." );
            // Create collection that will hold the running threads
            activeThreadCollection = new java.util.Vector();
            int i = 1;
            try
            {
                  java.net.ServerSocket socket = new java.net.ServerSocket( 8010 );
                  while ( true )
                  {
                        Socket incoming = socket.accept();
                        System.out.println( "Spawning client thread " + i );
                        ChatClient newThread = new ChatClient( incoming, i );
                        activeThreadCollection.addElement( newThread );
                        // Calls run() on the thread
                        newThread.start();
                        i++;
                  }
            }
            catch (Exception e)
            {
                  System.out.println( "Error: " + e );
            }
            System.out.println( SERVER_NAME + " Chat Server stopped." );
      }


      public static void doBroadCast( int id, String message )
      {
            // Create a enumeration of all active threads
            Enumeration enum = ChatServer.activeThreadCollection.elements();
            // Loop over all active threads
            while ( enum.hasMoreElements() )
            {
                  // Cast the current thread to a ChatClient
                  ChatClient currentThread = (ChatClient) enum.nextElement();

                  // broadcast the message to this thread
                  currentThread.putMessage( "Broadcast(" + id + "): " + message );
            }
      }

      
}// End: ChatServer Class

*************************************

package v1;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;

//Start: ChatClient Class
public class ChatClient extends Thread
{

      protected Socket incoming;
      protected int id;
      protected BufferedReader in;
      protected PrintWriter out;
      // Constant defining the maximum message length
      final int MAX_MESSAGE_LENGTH = 100;
 

      // Start: Constructor
      public ChatClient( Socket incoming, int id )
      {
            this.incoming = incoming;
            this.id = id;
            try
            {
                  if ( incoming != null )
                  {
                        in = new BufferedReader( new InputStreamReader( incoming.getInputStream() ) );           
                        out = new PrintWriter( new OutputStreamWriter( incoming.getOutputStream() ) );
                  }
            }
            catch (Exception e)
            {
                  System.out.println( "Error: " + e );
            }
      }// End: Constructor


      // Start: putMessage Locked Method
      public synchronized void putMessage( String message )
      {
            // if out is not null then print the message and flush
            if ( out != null )
            {
                  out.println( message );
                  out.flush();
            }
      }// End: putMessage Locked Method

      
      public boolean doValidate( String message )
      {

            // Cannot send empty message
            if ( message.trim().length() == 0  )
            {
                  putMessage( "the message cannot be empty" );
                  return false;
            }
            
            // Cannot send messages greater than the defined length
            if ( message.length() > MAX_MESSAGE_LENGTH )
            {
                  putMessage( "The message cannot be greater than " + MAX_MESSAGE_LENGTH + " characters." );
                  return false;
            }

            return true;
      
      }
      

      // Start: run method of the thread, called by start()
      public void run()
      {
            System.out.println( "Chat Client " + id + " started." );
            if ( in != null && out != null )
            {
                  putMessage( ChatServer.SERVER_NAME + " Chat Server. Enter BYE to exit." );
                  try
                  {
                        while ( true )
                        {
                              String message = in.readLine();
                              // Break out of this iteration if nothing has been passed
                              if ( message == null )
                              {
                                    break;
                              }
                              // If a string has been passed
                              else
                              {
                                    if ( message.trim().equals( "BYE" ) )
                                    {
                                          // Break out of the loop and close this thread
                                          break;
                                    }
                                    boolean shouldBroadcast = doValidate( message );
                                    if ( shouldBroadcast )
                                    {
                                          //putMessage( "Echo: " + message );
                                          // output on server
                                          System.out.println( "Received (" + id + "): " + message );
                                          // Broadcast to all clients
                                          ChatServer.doBroadCast( id, message );
                                    }
                              }
                        }
                        // close this thread
                        incoming.close();
                        // Remove the element from the thread collection
                        ChatServer.activeThreadCollection.removeElement( this );
                  }
                  catch ( IOException e ) {}
            }
            System.out.println( "Chat Client " + id + " stopped." );
      }
}//End: ChatClient Class

************************************

package v1;
import java.awt.*;

class UserInterface extends Frame {

      TextArea strTextArea = new TextArea();
      Button btnSubmit = new Button( "Send" );

      UserInterface()
      {
            super( "PacificFox Chat" );
            add( "Center", strTextArea );
            add( "South", btnSubmit );
            // size window to fit contents
            pack();
            // Show the window
            show();
      }

      public boolean action( Event evt, Object ob )
      {
            if ( evt.target == btnSubmit )
            {
                  String message = strTextArea.getText();
            }
            return true;
      }

      static public void main( String[] args)
      {
            new UserInterface();
      }
}
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 13751064
The ChatClient class anyway looks like a thread which will be at the *server*-side and which will *service* a client, but you still have to write a UI which will run at the *client*-side and connect to the server through a socket and do all communications.
0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
LVL 17

Author Comment

by:Tacobell777
ID: 13751142
ok, any thoughts code for that?

I guess its gotta be an applet, just a simple bit of code will get me going...
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 13751182
Applet to communicate over sockets? Why do you want to get into signing n' all (you'll face that problem if you want the Applet to connect to a remote server). Your UserInterface class already looks like something which will run at the client-side. You should just incorporate the socket-code into it.

For example, in the constructor of UserInterface (), try connecting:

Socket s = new Socket ( "IP address of server", 8010 ) ;

Obtain a handle to the output-stream and input-stream (or create a buffered-reader and print-writer over it the way you have done at the server-thread in the ChatClient class), and use it for communication with the server.
0
 
LVL 17

Author Comment

by:Tacobell777
ID: 13751273
Look I only just started with Java like this week, I've been reading for ages, but only got my hands dirty this week.
So I need a bit more than just pointers ;-)
0
 
LVL 17

Author Comment

by:Tacobell777
ID: 13751277
no applet, sounds fine to me too..
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 13751286
>> So I need a bit more than just pointers ;-)

Already gave it to you:)

Socket s = new Socket ( "IP Address", 8010 ) ;

Put that in the constructor of your UserInterface class. I hope that can be done? And as for the buffered-reader and print-writer, you have already done it in your ChatClient class - do it the same way in this class at the constructor.

In the action () method, send it to the server using:

pw.println ( message ) ; // where pw is the print-writer at the client-side

>> but only got my hands dirty this week.

Then, from your code, it looks like you're doing good :)
0
 
LVL 17

Author Comment

by:Tacobell777
ID: 13751295
keep in mind that this is to be embedded in a web page, I do not want clients to have to install anything..
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 13751302
Web-page? Where did that come from? I thought you had a Frame and were doing some socket-programming/ threading?
0
 
LVL 17

Author Comment

by:Tacobell777
ID: 13751508
Yeah ok, I did not mention that, fine, but I seriously don't see much help in your comment, you are even asking me if it can be done, how should I know? I probably haven't said it enough, I am a newbie, I have a vision but not sure how to get it achieved.
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 13751552
>> but I seriously don't see much help in your comment,

As per your current, if you want to run it as a Java application, I think my comment helps you out.

>>  you are even asking me if it can be done, how should I know?

I didn't ask you how it is to be done. I asked where did the web-page question come from because you did not state it initially in your question. You should make sure that you try to cover most of the points when you post your question if you want experts to help you with the exact problem.
0
 
LVL 17

Author Comment

by:Tacobell777
ID: 13751765
I quote "Put that in the constructor of your UserInterface class. I hope that can be done?"

And yes I agree, I need to explain myself well in the beginning.
I'll try and make some sense out of your comment tomorrow..
thanks
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 13751798
The UserInterface class already has a constructor:

>> UserInterface()
>>     {
>>          super( "PacificFox Chat" );
>>          add( "Center", strTextArea );

Why can't you add an extra line to it, which opens the socket?
0
 
LVL 17

Author Comment

by:Tacobell777
ID: 13756433
look at the code I posted and you tell me if that is all I need to do, to me it certainly does not look as simple as just adding a line to *it* which opens the socket.
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 13759576
>> as just adding a line to *it* which opens the socket

I also said:

>> for the buffered-reader and print-writer, you have already done it in your ChatClient class - do it the same way in this
>> class at the constructor

Since you had already done it in one class, I thought you will not face any problems in doing the same thing at another class.
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 13759983
Tacobell777,

You have to understand that we are not getting paid here for the help that we are giving you. We are not supposed to sit down and write all your code for you. We have our own work to do and in between that, we try to find out time to help people on this site. So sometimes, we would only be able to help you by giving you ideas and by mentioning how to go about your coding.
0
 
LVL 17

Author Comment

by:Tacobell777
ID: 13760095
Guys I seriously think that you need to chill, this area here is so freaking up tight its incredible, I know perfectly well we are not getting paid I answered 700 questions myself and am in the top 4 of the area I have knowledge in...

I have explained several times that I am a newbie (newbie as in I know crap all about what I am doing) and then I get short and no good responses, I am just fed up with it, in the area where we answer stuff we at least go through the trouble of helping newbies out and post some code.. 2 lines of suggestions is all I get here...

A little direction is all I asked for, is that to much to ask for here?
If so, I will find myself another way to get information, or maybe just dump Java all together as I have never had any good response from any JAva Developer..
0
 
LVL 17

Author Comment

by:Tacobell777
ID: 13760098
yeah, you convinced me mate, I deleted my other questions in this area...

Have a good one..

MFJD
0
 
LVL 92

Expert Comment

by:objects
ID: 13760109
Sorry for the brief comment, I answer a lot of questions and often some fall thru the cracks. For that I apologise.

As for some my comment, yes you were correct I misread your code that is the server side of the client application.
What you need is a client side class that handles talking to your server, and you'd pass an instance of *that* to your UI for it to use to communicate with the server.

And for some general direction in this area I'd suggest having a read of this article (or similiar) to get a bit of an overview:

http://www.javaworld.com/javaworld/jw-01-1997/jw-01-chat.html
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 13760207
>> 2 lines of suggestions is all I get here...

You had only 2 lines of suggestion in the accepted answer too.

As for my suggestion, I think that was all you needed to do - open a socket in the constructor of the UserInterface class, create a buffered-reader and print-writer, and talk to the server in the action () method using this:

>> pw.println ( message ) ; // where pw is the print-writer at the client-side

(which I already mentioned in one of my comments).

Can't provide detailed code right now as I don't have time and am occupied with work too. If you tried to come up with some code following the above suggestions, I could've helped you fix it.
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:
Suggested Courses
Course of the Month13 days, 16 hours left to enroll

807 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question