Creating a simple chat service. I have a TCPServer program, and a TCPClient program. The programs are multithreaded, and my client program is supposed to take input from the terminal and send it to the server program. I'm having trouble with a simple while loop, and I'm at my wit's end.
I've tried BufferedReader(using .readLine() and Scanner(using .nextLine()) to try and read in messages. When I use .nextLine() I get a "java.util.NoSuchElementException: No line found", and when I use .readLine() I get a "java.io.IOException: Stream closed". Here's my code (this is my thread class, within my client program):
private static class SendingThread extends Thread{
private Socket socket;
// private ArrayList<Socket> socketArray;
//Constructor
SendingThread(Socket socket){
this.socket = socket;
// this.socketArray = socketArray;
}
public void run() {
try {
System.out.println("SendingThread run method executed");
//Start timer
long startTime = System.currentTimeMillis();
//PrintWriter to pass messages to server
PrintWriter out = new PrintWriter(socket.getOutputStream(),true);
System.out.println("PrintWriter instantiated");
//Set up stream for keyboard entry
BufferedReader userEntry = new BufferedReader(new InputStreamReader(System.in));
System.out.println("BufferedReader instantiated");
// Get data from the user and send it to the server
String message;
do{
System.out.print("Enter message: ");
message = userEntry.readLine();
out.println(message);
} while (!message.equals("DONE"));
//Stop timer
long endTime = System.currentTimeMillis();
//Variables to measure time elapsed
long totalTime = endTime - startTime;
long milliseconds = totalTime % 1000;
long seconds = (totalTime / 1000) % 60;
long minutes = (totalTime / 60000) % 60;
long hours = (totalTime / 3600000) % 60;
//Receive final report and close connection
System.out.println("\n*** Information received from the server ***");
System.out.println("Length of session: " + hours + "::" + minutes + "::" + seconds + "::" + milliseconds);
} catch(IOException e) {
e.printStackTrace();
} finally {
try {
System.out.println("\n!!!!! Closing connection... !!!!!");
socket.close();
} catch(IOException e) {
System.out.println("Unable to disconnect!");
System.exit(1);
}
}
}
}
The problem is at the second line in my do-while loop, that's where it throws the error. It doesn't wait for my input, just terminates.