Welcome, Guest. Please login or register.
Did you miss your activation email?
Pages: [1]   Go Down
  Print  
Author Topic: Chat application problem  (Read 2572 times)
0 Members and 1 Guest are viewing this topic.
fembiz
Junior Member
*

Reputation: 0
Offline Offline
Posts: 2
Referrals: 0

Awards
« on: December 09, 2009, 08:25:31 PM »

Hi guys, I have designed a simple text chat application but i am expereincing problems with it.  I will explain.

Now I have 5 files.  IntroFrame.java, Server.java, Server_thread.java, Client.java, and ListClients.java

Now to run the appliication, you need to compile and then run the IntroFrame.java file.  This file opens a GUI that asks the user to select if the pc is the client or server.  So the server option is selected.  Once this is done, the server begins to run.  The next step is to run the client.  When the client is run, it must enter the server's hostname to connect, in this case it is 'localhost'.  once this has been entered, it asks the user to select a nickname.  PLEASE NOTE: for this part, the user has to enter 'Login: " followed by the desired nickname.  If the nickname is not in use, then the server accepts the client.  Once this is done the user can send messages by typing 'Post" followed by the message. 

Now the problem I have is with regards to running 2 clients.  When 2 clients are connected, if client A sends a message by typing 'Post...."  the message should be sent to all connected clients.  But in my application, the other clients do not receive the message.  I have gone through my code a million times and I can't figure out why it doesnt work.  I have pasted the Server.java, Server_thread.java, and Client.java file codes below.  Could someone please take a look at it and let me know what the problem is?  why does it not send the message to all connected clients?  Any help would be appreciated.  Thank you

Server.java

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

public class Server
{
    static Vector clients;
    static Socket clientSocket;
   
   public static void start_server()
   {
       
      //setting up the server socket to listen on a specified port
            
      clients = new Vector();     //this creates a reference to a vector object.  This will be used to store the list of clients connected to the server
      ServerSocket ss = null;     //this creates a reference to a ServerSocket object
                boolean listening = true;   //this creates a reference toa boolean object
      clientSocket = null;
      
      try
      {
                    ss = new ServerSocket(9999);    //this creates a new instance of the ServerSocket reference above.  The object is then set to listen on port 9999
               System.out.println("Server waiting for client connection...");
            }
      
      catch (IOException e)   //the ServerSocket object throws an exception if it cannot listen on the specified port i.e. if the port is being used for another service
      {                  
                    System.err.println("Unable to listen on port: 9999.");
                    System.exit(1);
                }
      
      //accepting a connection from a client
      
                    while (listening)   //a while loop is used to put the ServerSocket in an indefinite listening state
      
         try
         {
            //System.out.println("Server waiting for client connection...");
            clientSocket = ss.accept();
            System.out.println( "Connection established");
            System.out.println("Server waiting for client login request...");
            Server_thread sthread = new Server_thread(clientSocket);
                                clients.add(sthread);   //the newly connected client is then added to the vector to maintain a current list of connected clients
            sthread.start();        //in order to handle mutliple clients, a thread object is created and assigned to each client.  This is how each client will communicate with server.
            
                        }

                        catch (IOException e)
                        {
                            System.out.println("IOaccept "+e);
         }
           
    }
}



Server_thread.java

import java.net.*;
import java.io.*;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Server_thread extends Thread
{
    Socket clientSocket;                    //creates a reference to a Socket object
    Socket sock;
    String nick_name;                       //creates a reference toa string object.  This will be used to store the nick name tha the client selects
    PrintWriter msg_out; //I/O              //creates a reference to a printwriter object.  This will handle the output
    Scanner msg_in;                         //creates a reference to a scanner object.  This will handle the input
    public static Boolean connect_status;   //creates a reference to a boolean object
   

       Server_thread(Socket sock)   //constructor method passes a Socket object parameter
   
   {
            super("Server_thread"); //calls the constructor method for the super class
            connect_status= false;  //sets the connect_status object to false therefore requiring the client to register
            nick_name = "";
            clientSocket = sock;

        try
      {
         //sindesi I/O antikeimenwn me ta streams tou socket
         msg_out = new PrintWriter(clientSocket.getOutputStream(), true);
         msg_in =  new Scanner (clientSocket.getInputStream());
      }
      catch (Exception e)
      {
         System.out.println(e);
      }
        }

          synchronized void send(String msg)
        {
            msg_out.println(msg);
        }
   
   //setting up communication betweek the server and the client
   
    void begin()
    {
      
      //start the conversation with the client using the established protocols as specified in the Protocol class
      
         
            //Protocol prot = new Protocol();    //a new instance of the protocol class is created.  This specifies the format and sequence of the messages that will be sent between the client and server
            //output = prot.processInput(null);  //client communication from the server is initiated here.  This is done by writing to the socket
            //msg_out.println(output);

      //while ((input = msg_in.nextLine()) != null)   //performs communication with client by writing to the socket and reading from it
         
              //while ((msg_in.nextLine()) != null)
      try
      {
                    //msg_in =  new Scanner (clientSocket.getInputStream());            //gets the socket's input stream
                    //msg_out = new PrintWriter(clientSocket.getOutputStream(), true);  //gets the socket's output stream
                              
         while (true)
         {
                            String message = msg_in.nextLine();       //reads the input from the client
             System.out.println(message);
                            //send(message);
                            if (message.startsWith("Login"))          //if the client's message starts with login, the register method is called
                            {
                                register(message);
                            }
                         
                           else
                            {
                                msg_in.close();
            msg_out.close();
            sock.close();
                                System.exit(1);
             }
               
                        }
         
                   }
         
                    catch (IOException e)
                    {
                        e.printStackTrace();
                    }

         
   }
         
     
         
   public void run()
        {
           begin();
        }

        //method that is used to register a new client requesting to join the network
   boolean register(String msg)
   {

            if (connect_status)     //if the client is already registered, the message below is displayed
            {
                msg_out.println("You are already connected!");
            return true;
            }

            boolean exists = false;
            //System.out.println("Login" + msg.substring(5, msg.length()));  //the substring method is called to reduce the message sent to omit the 'Login' part and simply display the user's desired nick name
         
                //the server checks through the clients list vector using a loop.
                //for each index in the vector, the connected client nick name is obtained by calling the get() method
                //a temporary thread is then created and the connected client object is assigned to it
                //the nick name of the temporary thread is then checked against the requested nick name.
                //if they are the same, then it means the new client's desired nick name is already in use
                //a break occurs and the server displays a new message requesting the user to select a different nick name

                for (int i = 0;i < Server.clients.size();i++)
      {
                    if (Server.clients.get(i) != null)
                    {
                        //System.out.println(msg.substring(7, msg.length()));
         //System.out.println(msg);
         Server_thread temp_thread = (Server_thread)Server.clients.get(i);
                  
         if ((temp_thread.nick_name).equals(msg.substring(7, msg.length())))
                        {
                            exists = true;
                            break;
         }

                    }
      }

                    if (exists)
                    {
                        msg_out.println("Choose a different nick name");
                    }

                    //however, if the temprorary thread object's nick name variable does not match the desired nick name
                    //the connection status is set to 'true' and the client's nick name is registered with the server
                    //the server then creates an instance of the ListClients class and calls the List() method on it
                    //in order to produce an updated list of currently connected clients and output the list to the client

                    else
                    {
                        connect_status = true;
                        nick_name = msg.substring(7,msg.length());
         ListClients lc = new ListClients();
                        lc.List();
         //System.out.println(lc.client_list);
         System.out.println("New client " + nick_name + " has been successfuly registered to server");
         //ListenerThread listener = new ListenerThread(clientSocket, nick_name);
                        //Thread lst = new Thread(nick_name);
                        //lst.listen();
                        //lst.start();
                        //listen();


                       // for (int i = 0;i < Server.clients.size();i++)
                        //{
                            //if (Server.clients.get(i) != null)
                           // {
                        int i = Server.clients.indexOf(this);
                        Server_thread temp_thread = (Server_thread)Server.clients.get(i);
                        System.out.println("Wating for messages...");
                        temp_thread.listen();
                       
                        //System.out.println(lst);
                     
                            // }
                       
                             //}

                    }
               
                    return true;
         
   }

        //class ListenerThread extends Thread
       
        // Socket clientSocket;
        // Scanner str_in;
       //  boolean listen = true;
        // String nick_name;

       //  ListenerThread(Socket clientSocket, String nick_name)
       //  {
       //   this.clientSocket = Server_thread.clientSocket;
       //   this.nick_name = Server_thread.nick_name;//boolean sendAll(String msg)
       
       //  }
   
         
        public boolean listen()
        {
           boolean listening = true;
           
            try
            {
                msg_in =  new Scanner (clientSocket.getInputStream());
                msg_out = new PrintWriter(clientSocket.getOutputStream(), true);
            }
            catch(Exception e)
            {
            System.out.println("Unable to get unput stream");
            }
   
            while (listening = true)

             if (Server_thread.connect_status = true)
                {
                    String str = msg_in.nextLine();
                        //String message;
                    if (str.startsWith("Post"))
         {
                           //sendAll(message);
                           //System.out.println(str.substring(5, str.length()));
                           //int i = Server.clients.indexOf(this);
                           //Server_thread tt = (Server_thread)Server.clients.get(i);
                           send("Recieve "+ nick_name+": " +str.substring(5, str.length()));
                           System.out.println(str);
                         
                           //send("Recieve "+ nick_name+": " +str.substring(5, str.length()));
                           //System.exit(1);
                           //str = null;
                           listening = true;
                           
         }
                    //return;
                }
           
                return listening;
   
   
     
            }
         
       
       
         
   
}
      

Client.java

import java.net.*;
import java.io.*;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Client
{

    public static void main(String[] args) throws IOException {
    //public void run()
    {
        Socket sock = null;
        PrintWriter msg_out = null;
        Scanner msg_in = null;
   String hostname = null;
            
        try {
         
         Scanner host_pc = new Scanner(System.in);
                        //msg_in =  new Scanner (sock.getInputStream());
                        //msg_in =  new Scanner (System.in);
         System.out.print("\n\nEnter host name: ");
         hostname = host_pc.nextLine();
                        //hostname = msg_in.nextLine();
         sock= new Socket(hostname, 9999);
         msg_out = new PrintWriter(sock.getOutputStream(), true);
                        msg_in =  new Scanner (sock.getInputStream());
         System.out.print("\n\nSelect a nick name: ");
       
            }
        catch (UnknownHostException e)
        {
            System.err.println("Error!  Could not connect to host: " + hostname);
            //System.exit(1);
         return;
         
        }
        catch (IOException e)
        {
            System.err.println("Error!  Could not get the input and output streams for the connection to:  " + hostname);
                               
            System.exit(1);
        }
        // Send some data to the server.

        //System.out.println("\n\nEnter message: ");
        //String toServer = "Are you there, Server?";
        //msg_out.write(toServer);
        //msg_out.newLine();
        //msg_out.flush();

// Wait for a response from the server and display it.
       
        Scanner input = new Scanner(System.in);
   
        String userInput;

   while ((userInput = input.nextLine()) != null)
        {



            //System.exit(1);
            msg_out.println(userInput);
       System.out.println(msg_in.nextLine());
            // Use a BufferedReader to read data from the server.
            //input = new Scanner (sock.getInputStream());
            //String fromServer = msg_in.nextLine();
            //System.out.println("FromServer: " + fromServer);
            //String fromServer = msg_in.nextLine();
            //System.out.println("FromServer: " + fromServer);
   }

   msg_out.close();
   msg_in.close();
   input.close();
        try {
            sock.close();
        } catch (IOException ex) {
            Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

}
}
Logged
Arkie
Javaforums.net Admin
Senior Member
*

Reputation: 16
Developer @ Javaforums.net
Offline Offline
Posts: 2593
Referrals: 13

WWW Awards
« Reply #1 on: December 10, 2009, 04:27:16 AM »

please use the code tags, its horrible to read your code.
Logged

Java and .NET developer

To students: It doesn't matter how hard you've studied; the material won't be on the exam anyway.

Fan of http://www.retardedweblogger.com
Oh man, too much stuff to do in so little time.

http://img222.imageshack....707/arkietomatoesmall.jpg
Blizzcon 2k9 Grubby and Cassandra Ng engaged ! <3
Triple D, eerste Denken Dan Doen
Pages: [1]   Go Up
  Print  
 
Jump to:  

Your Ad Here