2

I'm using sockets to chat as part of a large application, however so you can read it easier i have made 2 classes that show the problem. I have a server and a client, the server opens a socket and waits for a client to connect once connected it sends them a welcome message. On the client side they display the welcome message then enter a loop to write to the PrintWriter. On the server side it will now enter a loop that constantly displays text from the bufferedReader however nothing is printing out, not sure if i'm being stupid but think it needs a fresh pair of eyes, Thanks.

public class Server {

public static boolean running = true;
public static PrintWriter out;
public static BufferedReader in;

public static void main(String[] args) throws IOException {
    ServerSocket s = new ServerSocket(1932);
    while (true) {
        Socket cs = s.accept();
        out = new PrintWriter(cs.getOutputStream(), true);
        in = new BufferedReader(new InputStreamReader(cs.getInputStream()));
        out.println("Welcome");
        out.flush();
        while (running == true) {
            String input = in.readLine();
            if (input.equals("QUIT")) {
                System.out.println("theyve gone :( ");
                cs.close();
                running = false;
            } else {
                System.out.println(input);
            }

          }

       }
    }
}



public class Client {

public static boolean running = true;
public static PrintWriter out;
public static BufferedReader in;
public static Scanner scan;

public static void main (String [] args) throws IOException{

    Socket so = new Socket("localhost", 1932);
    out = new PrintWriter(so.getOutputStream());
    in = new BufferedReader(new InputStreamReader(so.getInputStream()));
    System.out.println("TYPE QUIT TO LEAVE ");
    System.out.println(in.readLine());
    while(true){
        scan = new Scanner(System.in);
        String message = scan.next();
        out.print(message);
        out.flush();


    }
  }  

}
1
  • readLine() reads until you write a newline. If you don't write one it read until you close the connection or run out of memory. Feb 27, 2015 at 17:37

1 Answer 1

3

In the server, you're reading the next line:

String input = in.readLine();

So the server blocks until the end of line is reached (or the stream is closed).

And on the client, you never send any end of line:

out.print(message);
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.