创建简单的聊天服务。我有一个TCPServer程序和一个TCPClient程序。程序是多线程的,我的客户端程序应该从终端获取输入并将其发送到服务器程序。我在使用简单的while循环时遇到了麻烦,而且我已经结束了。
我尝试过BufferedReader(使用.readLine()和Scanner(使用.nextLine())来尝试读取消息。当我使用.nextLine()时,我得到一个" java.util。 NoSuchElementException:找不到行",当我使用.readLine()时,我得到一个" java.io.IOException:Stream closed"。这是我的代码(这是我的线程类,在我的客户端程序中):
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);
}
}
}
}
问题出在我的do-while循环的第二行,它会抛出错误。它不会等待我的输入,只是终止。