我有一个服务器/客户端聊天室。当客户端连接到服务器并发送消息时,客户端程序会打印出它发送的消息,但在另一个连接到服务器的客户端程序上,它不会打印出,直到用户按下“输入”键.
在客户端:
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);
}
}
顺便说一句 - server.showAll(message, output); 方法是这样的:
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。
那么:关于如何立即打印消息的任何想法?
感谢您的任何帮助。