Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: BufferedReader and OutputStream

Tags:

java

I've got the following code, I'm trying to send data text by sockets. But when I try to send via PrintWriter, my client does nothing and it stops at in.readLine(). However when I use simply OutputStream and send it as bytes, my client doesn't have any problem with reading. Is it possible to as I want ?

        out = new PrintWriter(sock.getOutputStream());
        in = new BufferedReader(new InputStreamReader(sock.getInputStream()));

        while (true) {
            System.out.println("SERVER-THREAD: IP "
                    + sock.getInetAddress().getHostAddress());
            out.write(marshall() + "\n");
            Thread.sleep(1000);
        }

//Client

            in = new BufferedReader(new InputStreamReader(sock.getInputStream()));
            out = new PrintWriter(sock.getOutputStream());

            while (updateList) {
                System.out.println("Before");
                String inputip = in.readLine();
                System.out.println("CLIENT: " + inputip);
                //unmarshall(in);
                System.out.println("After");
                Thread.sleep(1000);
            }
like image 444
ashur Avatar asked Feb 13 '26 22:02

ashur


2 Answers

PrintWriter buffers the data to be written so it will not do so until the buffer is full. You need to call flush here

out.flush();
like image 72
Reimeus Avatar answered Feb 16 '26 10:02

Reimeus


When you perform a readLine() it waits until it has a read a whole line. i.e. a new line.

Your send is sending text without a newline so the receive waits for something which will not happen.

A more basic problem is that you are mixing text and binary which is more likely to confuse than be useful.

I suggest you write text with PrintWriter.println() which you can read with BufferedReader.readLine().

like image 40
Peter Lawrey Avatar answered Feb 16 '26 10:02

Peter Lawrey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!