Avatar of tequila_dude
tequila_dude
 asked on

threads

hI,

can someone tell me why he only wants to print the name of the user who asked it (/list) and not the other users ?
static Vector chatters = new Vector( );=> this vector does the job
static Vector whoOnline = new Vector( );=>this one not :(

thxs alot

the code
*********************************************************
// Chatter.java

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

      // *********************************************
      // * Thread, opgestart voor elke nieuwe client *
      // *********************************************

public class Chatter extends Thread // dit is een subklasse van Thread
{
  //declaratie van variabelen
  static Vector chatters = new Vector( );//Vector, omdat een vector kan worden verdeeld over meerdere toepassingsthreads
  static Vector whoOnline = new Vector( );//static variabelen worden authomatisch geshared tussen threads
  private Socket socket;
  private BufferedReader in;
  private PrintWriter out;
  private String info;
  private String name;
  private String brol;
  private String sex;
 

    public Chatter(Socket socket) throws IOException
    {      //zet de meegegeven socket in de lokale variabele
        this.socket = socket;
        // creër een in- en uitvoerstroom
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            out = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
    }//einde Chatter constructor
   
    //run-methode van klasse Thread wordt overschreven (overridden)
    public void run()
    {      
          String line= " ";
            synchronized(chatters) // zodat geen 2 threads tergelijkertijd deze functie kunnen gebruiken
            {
                chatters.addElement(this); //this == object (met socket,input en outputstream dus)
             }
      
            try
            {      
                  //zolang bericht minstens 1 karater bevat, doe :
                while(true)//!(line = in.readLine()).equalsIgnoreCase("/quit"))
                {
                      line = in.readLine();
                      if(line.endsWith("$info$"))
                      {
                            setClientInfo(line);
                      }
                      else if(line.endsWith("/list"))
                      {
                            printAllOnlineClients();
                      }
                      else
                      {                                        
                              System.out.println(line);// schrijf naar client
                              for(int i = 0; i < chatters.size(); i++)//schrijf naar alle ander clients
                              {      
                                    synchronized(chatters)
                                    {
                                          Chatter sendMessage = (Chatter)chatters.elementAt(i);
                                             sendMessage.out.println(line + "\r");
                                          sendMessage.out.flush();
                                    }
                              }
                        }
                }// einde while-lus
                
            } catch(IOException ioe)
                  {
                        System.out.println("Er heeft zich een fout voorgedaan in de communicatie!");
                      //ioe.printStackTrace();
                  } finally
                        {
                            try
                            {
                                    in.close();
                                    out.close();
                                    socket.close();
                            } catch(IOException ioe)
                                  {
                                  } finally
                                        {
                                                synchronized(chatters)
                                                {
                                                      //verwijder client
                                                    chatters.removeElement(this);
                                                }
                                        }
                        }            
    }//einde run-methode
   
    public void setClientInfo(String info)
    {
          StringTokenizer st = new StringTokenizer(info);
          name = st.nextToken();
          sex  = st.nextToken();
          brol = st.nextToken();
          synchronized(whoOnline)
            {
                whoOnline.addElement(name);
          }         
    }
          
    public void printAllOnlineClients()
    {
          for(int i = 0; i < whoOnline.size(); i++)
                              {      
                                  synchronized(whoOnline)
                                    {
                                          String online = (String)whoOnline.elementAt(i);
                                          synchronized(chatters)
                                          {
                                          Chatter sendMessage = (Chatter)chatters.elementAt(i);
                                             sendMessage.out.println(online + "\r");
                                          sendMessage.out.flush();
                                           }
                                          
                                    }      
                            }
    }
   
}//einde klasse Chatter
Java

Avatar of undefined
Last Comment
Mick Barry

8/22/2022 - Mon
tequila_dude

ASKER
with this he only prints the first name but not the rest nomatter how many clients online..

please help me!
thxs

code:
**********************************************************

public void printAllOnlineClients()
    {
         for(int i = 0; i < chatters.size(); i++)
         {
             
                             synchronized(whoOnline)
                              {
                                   //String online = (String)whoOnline.elementAt(i);
                                   synchronized(chatters)
                                   {
                                   Chatter sendMessage = (Chatter)chatters.elementAt(i);
                                   for(int y = 0; y < chatters.size(); y++)
                                   {    
                                        ClientInfo temp = (ClientInfo)whoOnline.elementAt(y);
                                        sendMessage.out.println(temp.name);// + "\r");
                                   }
                                    sendMessage.out.flush();
                                    }
                                   
                              }    
         }
    }
   
   
}//einde klasse Chatter
Mick Barry

Check that setClientInfo() is getting called.
Tommy Braas

If you change the;

   if(line.endsWith("$info$"))

to

   if(line.indexOf("$info$")!=-1)

then that if statement will be executed even if there is some garbage at the end of the string. You could do the same for the following statement;

   else if(line.endsWith("/list"))

A debugger is also recommended to use in situations like this one.
Your help has saved me hundreds of hours of internet surfing.
fblack61
Mick Barry

> if there is some garbage at the end of the string.

Why would there be garbage at the end of the string?
tequila_dude

ASKER
setClientInfo is getting called and the statements are being executed when they should be (not always only when required!)
tequila_dude

ASKER
setClientInfo => if this wouldn't get called there wouldn(t even be one name :)
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
Mick Barry

The two versions of printAllOnlineClients() you posted are different, which one are you currently using?

Although both appear incorrect as they both using i to index both the whoOnline and chatters vectors.

Can you print the values of both vectors when printAllOnlineClients() is called:

public void printAllOnlineClients()
{
   System.out.println(chatters.size()+":"+chatters);
   System.out.println(whoOnline.size()+":"+whoOnline);
   ...
       

sciuriware

Als je weer iets post, vertaal dan even je comments in het Engels, dan heeft de rest van de wereld er ook wat aan.
{{ Please translate your comments }}
;JOOP!
tequila_dude

ASKER
i'm using the second one now!

output of
System.out.println(chatters.size()+":"+chatters);
and System.out.println(whoOnline.size()+":"+whoOnline);
=>

2:[Thread[Thread-1,5,main], Thread[Thread-2,5,main]]
2:[ClientInfo@13e8d89, ClientInfo@1be2d65]

is this right?

btw this uses index y => ClientInfo temp = (ClientInfo)whoOnline.elementAt(y);
don't kno what you mean with =>they both using i
I started with Experts Exchange in 2004 and it's been a mainstay of my professional computing life since. It helped me launch a career as a programmer / Oracle data analyst
William Peck
Mick Barry

Contents of the Vector look ok, so I'd say the problems more likely in the sending or recieving of the message.
You can confirm with the following:

   ...
   for(int y = 0; y < chatters.size(); y++)
   {    
     ClientInfo temp = (ClientInfo)whoOnline.elementAt(y);
     System.out.println("Sending "+temp.name);
     sendMessage.out.println(temp.name);// + "\r");
   }
   ...
tequila_dude

ASKER
yep confirmed!!

when 2 users eg lennert and jef are connected

on server he gives:
-------------------
Sending lennert
Sending jef

on client:
----------
lennert

tequila_dude

ASKER
when i put it like this:

for(int y = 0;y < whoOnline.size();y++)
{
Chatter sendMessage = (Chatter)chatters.elementAt(clientIndex);
ClientInfo temp = (ClientInfo)whoOnline.elementAt(y);
System.out.println("Sending "+temp.name);
sendMessage.out.write(temp.name);

}

he print's all the names but on 1 row
eg: SaveSeanPeter

if i change the following line: with an "\n" or a "\r"
eg : sendMessage.out.write(temp.name+"\n");  

he only print's out the first name :(

at the other end (client)the following code reads the data and sets it in a textarea
**********************************************************
String message = " ";
        while(true)
                  {
                     message = leesData();
                     aTextArea.append(message+"\r");
                }
private String leesData(){
           String s=null;
        try{
                  in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                  s = in.readLine();
                  System.out.println(s);
             }catch(Exception e){System.out.println("test3");
                 //removeSelf();
                return null;     }

        return s;
        }//einde leesData()      

Any idea's ? almost there...... :)

thxs
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
Mick Barry

You need to use the same BufferedReader to read *all* the names, not create a new one to read each name.

BufferedReader is *buffered* so it arbitrary amounts of reads data from the stream into an internal buffer, and then reads a line from that buffer.
tequila_dude

ASKER
i don't extactly understand...
can you give an example please?

client has only one buffered reader..
the method  leesData() is used to read all incoming data..
ASKER CERTIFIED SOLUTION
Mick Barry

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.