Hello,

I have a following loop in the client side to read strings from InputStreamReader of a socket

try{
kkSocket = new Socket("yadav-notebook", 1357);
in = new BufferedReader(new InputStreamReader(kkSocket.getInputStream()));
}catch(UnknownHostException e){}
String fromServer=null;
while((fromServer=in.readLine())!=null){
System.out.println(fromServer);
}

I want to display the string typed by a client to all the clients connected to a multi-threaded server. Why do I have to hit enter to read one string at a time? What is wrong in the while loop above?

The server codes are given below.

public class Talker implements Runnable {
Socket linkto; // the socket
PrintWriter out; // the output streams
BufferedReader bin;
int id; // i.d. of the connection
String from_name; // name of host connecting
..
public static void main(String [] args) {
// Parent thread - create a server socket and await a connection
ServerSocket ss = null;
Socket s = null;
connectiontable = new Vector();

try {
ss = new ServerSocket(1357);

while ((s=ss.accept())!= null) {
Talker now;
Thread current = new Thread(now = new Talker(s));
current.setDaemon(true);
connectiontable.addElement(now); // Save talker into vector ..

current.start(); // start the user's thread

}
}
catch (Exception e) {
System.out.println(e);
}
}
Talker (Socket from) {
id = nextid++;
linkto = from;
InetAddress source = linkto.getInetAddress();
from_name = source.getHostName();
try {
out = new PrintWriter(new OutputStreamWriter
(linkto.getOutputStream()));
bin = new BufferedReader(new InputStreamReader
(linkto.getInputStream()));
}
catch (Exception e) {e.printStackTrace();}
}
..
public void run () {
String line = " [User has just logged in] ";

while (true) {
boolean done=false;

// read a line from the user

if (line == null) {
try {
out.print(">: "); //prompt,flush,read
out.flush();
line = bin.readLine();
} catch (Exception e) {
System.out.println(e);
done = true; // force exit if there's a problem
}
}//end if

// echo the line (with a header) to all users

String outline = from_name+" "+id+": "+line;
System.out.println(outline);
int k;
for (k=0;k<connectiontable.size();k++) {
Talker person = (Talker)connectiontable.elementAt(k);
person.out.println(outline);
person.out.flush(); // Vital - ensure it is sent!
}
if (done) {
connectiontable.removeElement(this);
try {
out.close(); // closes needed to terminate connection
bin.close(); // otherwise user's window goes mute
linkto.close();
}catch (Exception e) {}
break;
}//end if
line = null;
}//end while
}//end run