?
Solved

threads

Posted on 2003-02-28
15
Medium Priority
?
218 Views
Last Modified: 2010-03-31
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
0
Comment
Question by:tequila_dude
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
15 Comments
 

Author Comment

by:tequila_dude
ID: 8045197
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
0
 
LVL 92

Expert Comment

by:objects
ID: 8045765
Check that setClientInfo() is getting called.
0
 
LVL 14

Expert Comment

by:Tommy Braas
ID: 8045912
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.
0
Optimize your web performance

What's in the eBook?
- Full list of reasons for poor performance
- Ultimate measures to speed things up
- Primary web monitoring types
- KPIs you should be monitoring in order to increase your ROI

 
LVL 92

Expert Comment

by:objects
ID: 8045939
> if there is some garbage at the end of the string.

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

Author Comment

by:tequila_dude
ID: 8045953
setClientInfo is getting called and the statements are being executed when they should be (not always only when required!)
0
 

Author Comment

by:tequila_dude
ID: 8045955
setClientInfo => if this wouldn't get called there wouldn(t even be one name :)
0
 
LVL 92

Expert Comment

by:objects
ID: 8045978
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);
   ...
       

0
 
LVL 24

Expert Comment

by:sciuriware
ID: 8046953
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!
0
 

Author Comment

by:tequila_dude
ID: 8047197
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
0
 
LVL 92

Expert Comment

by:objects
ID: 8048988
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");
   }
   ...
0
 

Author Comment

by:tequila_dude
ID: 8051339
yep confirmed!!

when 2 users eg lennert and jef are connected

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

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

0
 

Author Comment

by:tequila_dude
ID: 8051375
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
0
 
LVL 92

Expert Comment

by:objects
ID: 8054100
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.
0
 

Author Comment

by:tequila_dude
ID: 8054198
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..
0
 
LVL 92

Accepted Solution

by:
objects earned 300 total points
ID: 8054210
Ev erytime leesData is called (ie. for each line) you create a new BufferedReader:

private String leesData(){
  String s=null;
  try{
    in = new BufferedReader(new InputStreamReader(socket.getInputStream()));  // <--- new reader for each line
                 

0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

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

Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
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:
The viewer will learn how to implement Singleton Design Pattern in Java.
Suggested Courses
Course of the Month11 days, 20 hours left to enroll

752 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