I want to have Server - Client relation. Once client gets connected to a server, server sends a message to a client every 1.5 seconds. Server doesn't do anything with messages from client for simplicity. In client's code, I want to use System.in to send messages to server (which don't mean anything) and when I send it, I want to read server's response (all accumulated messages from server). Code is not a snippet, but "real code".
Client:
public class ClientClass {
public static final String IP_ADDRESS = "127.0.0.1";
public static final int PORT = 9090;
public static void main (String[] args) throws IOException {
Socket socket = new Socket (IP_ADDRESS,PORT);
PrintWriter output = new PrintWriter (socket.getOutputStream (),true);
BufferedReader input = new BufferedReader (new InputStreamReader (socket.getInputStream ()));
BufferedReader keyboard = new BufferedReader (new InputStreamReader (System.in));
while (true){
System.out.println ("Enter message you want to send to server:");
String msg = keyboard.readLine ();
output.println (msg);
String serverResponses = input.readLine ();
while (serverResponses!=null){
System.out.println (serverResponses);
serverResponses=input.readLine ();
}
}
}
}
Server:
public class ServerClass {
public static int PORT = 9090;
public static void main (String[] args) throws IOException, InterruptedException {
ServerSocket server = new ServerSocket (PORT);
Socket client = server.accept ();
PrintWriter output = new PrintWriter (client.getOutputStream (),true);
while (true){
output.println ("hello from server");
Thread.sleep (1500);
}
}
}
//My comment: readLine() method in client is blocking, so I can't read server's messages until I actually read something from keyboard. That is why I have loop to "pick up" all lines from inputStream. I expect that once I read all the lines, variable stringResponses gets null and breaks from inner while loop. Then I thought that I would get a print to console of "enter message you want to send to server" found in outer loop. Unfortunately, my code never breaks out from inner while loop and I want to know why. How is it never null, when I am writing to a stream every 1.5s, meaning there is plenty of time for it to be null and break from loop.
ACTUAL OUTPUT:
Enter message you want to send to server:
hey! //this is what I typed
hello from server
hello from server
hello from server
//these three popped immediately, as they accumulated.
hello from server
hello from server
hello from server
hello from server
//keeps printing "hello from server" every 1.5s and never comes back to "enter your message" -WHY?