我有一個服務器/客戶端聊天室。當客戶端連接到服務器併發送消息時,客戶端程序會打印它發送的消息,但是在連接到服務器的另一個客戶端程序中,它不會打印出來,直到用戶按下「輸入」鍵。如何直接打印出消息? java聊天室
在客戶端:
try {
//Strings to hold messages in and out:
String userinput, serverinput;
//Getting input from the user:
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
//Messages from the server will be printed to the console, messages from console will be sent to the socket:
while(true) {
userinput = input.readLine();
serverout.println(username + "> " + userinput);
serverinput = clientin.readLine();
System.out.println(serverinput);
}
}
在服務器端:
public void run() {
PrintWriter output = null;
BufferedReader input = null;
String message;
SchoolRoomServer server = new SchoolRoomServer();;
try {
//i/o for clients:
output = new PrintWriter(socket.getOutputStream());
input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (IOException ioe) {
System.err.println(ioe);
System.exit(1);
}
try {
while((message = input.readLine()) != null) {
server.showAll(message, output);
}
} catch (IOException ioe) {
System.err.println(ioe);
System.err.println("Damn errors.");
System.exit(1);
}
}
通過way-的server.showAll(消息,輸出);方法是這樣的:
public void showAll(String msg, PrintWriter printwriter) {
for(int i = 0; i < listWriters.size(); i++) {
if(listWriters.get(i) != printwriter) {
listWriters.get(i).println(msg);
}
}
}
listWriters是PrintWriters的ArrayList,它獲取與客戶端的新的線程被該客戶機由每一個時間相關聯一個PrintWriter。
因此:關於如何立即打印出消息的任何想法?
謝謝你的幫助。
順便說一句,我對Java很新穎 - 我會在哪裏使用flush()方法直接打印出來? –